![](/img/trans.png)
[英]What's the best way to share user accounts between the application and an engine?
[英]Share user object between several react_components
除了將其掛在 window 之外,在多個react_component
之間共享用戶 object 的最佳方法是什么?
例如 -
<%= react_component("HelloWorld1", { user: @user }) %>
<%= react_component("HelloWorld2", { user: @user }) %>
如果你想結合 HTML.ERB 和 React,我認為你目前擁有的方式是最好的方式。
就像在處理純 React 時不能一次將 prop 傳遞給兩個組件一樣,我認為在這種情況下你也不能這樣做。
注意:我不確定以下內容會如何影響 SEO。
您可以將 Rails 應用程序用作 API,並使用 static_pages 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.