问题描述
除了将用户对象挂在窗口之外,在多个 react_component
之间共享用户对象的最佳方式是什么?
例如 -
<%= react_component("HelloWorld1",{ user: @user }) %>
<%= react_component("HelloWorld2",{ user: @user }) %>
解决方法
如果你在前端使用 React 和 HTML.ERB
如果你想结合 HTML.ERB 和 React,我认为你目前拥有的方式是最好的方式。
就像在处理纯 React 时你不能一次将一个 prop 传递给两个组件一样,我认为在这种情况下你也不能这样做。
如果你只在前端使用 React
注意:我不确定以下内容会如何影响 SEO。
您可以将 Rails 应用程序用作 API,并使用 static_pages#root
(或类似内容)中的单个 HTML 标记显示您的 React 应用程序。然后使用 react-router-dom
在前端路由和更改页面。
这样您就不必继续渲染 html.erb
模板,您可以将实例变量传递给这些模板。您将使用 API 请求获取数据并对其进行修改。
额外的细节
如果您选择使用第二种方法(使用 react-router-dom
),则文件可能类似于以下内容:
routes.rb
Rails.application.routes.draw do
namespace :api,default: { format: :json } do
resources :users,only: [:index,:show,:create,:destroy]
# ...
end
root to: 'static_pages#root'
end
app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
def root
end
end
app/views/static_pages/root.html.erb
<main>
<%= react_component("App") %>
</main>
app/javascript/components/App.jsx
import React,{ useState,useEffect } from 'react';
import {Switch,Route} from 'react-router-dom';
import { Auth } from './auth/Auth.jsx';
import { HelloWorld1 } from './hello/world1/HelloWorld1.jsx';
import { HelloWorld2 } from './hello/world1/HelloWorld2.jsx';
const App = () => {
const [user,setUser] = useState(null);
if (!user) {
return (
<Auth setUser={setUser} />
);
}
return (
<Switch>
<Route
exact
path="/hello/world1"
render={(props) => <HelloWorld1 user={user} {...props} />}
/>
<Route
exact
path="/hello/world2"
render={(props) => <HelloWorld2 user={user} {...props} />}
/>
{/* ... */}
</Switch>
};
export default App;