我如何在AppContainer和Home組件之間共享狀態?將容器組件中的道具傳遞給嵌套的路由組件
例如,我想將結果對象置於AppContainer狀態以將其傳遞給所有其他組件。
在這個程序中,我沒有使用Redux。
我試着使用React.cloneElement在AppContainer但產生一個錯誤:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
index.js
<Router history={browserHistory}>
<AppContainer>
<Route path="/" component={Home} />
<Route path="search" component={Search} />
</AppContainer>
</Router>
AppContainer.js
render() {
return (
<div className="containerApp">
{this.props.children}
</div>
);
}
一般來說,這是不是從最佳實踐的立場點(特別是因爲你不使用終極版)。可你給的你是什麼樣的想法是個好主意試圖完成?更有可能的是,比通過路由器傳遞狀態更好。 – Teedub
好的。謝謝。例如在家庭組件我有一個搜索表單,我檢索結果,然後我將這個結果添加到組件狀態。但我想在搜索組件中得到這個結果。告訴我,如果我有更好的解釋... –
我不認爲你可以將狀態從父組件傳遞到子組件的狀態,無論是使用上下文(這很麻煩),或者你將狀態作爲道具傳遞給子組件。這很容易做到。爲什麼複雜的事情:P –