[英]How do I retain state in a React component that gets mounted and unmounted?
Right now I have three main components in a sort of tab layout with a header on top, and which one of them is active is controlled in the top-level App component with a very simple hash router. 现在,我具有三个主要组件,它们处于一种选项卡布局中,其中一个标题位于顶部,并且其中一个活跃的组件是通过一个非常简单的哈希路由器在顶级App组件中进行控制的。
Now if I set a state in my Profile component that state will get thrown out if i switch to one of the other components. 现在,如果我在Profile组件中设置了一个状态,那么当我切换到其他组件之一时,该状态将被抛出。
How can I prevent that? 我该如何预防? Should I put the state on the App component instead or is this where something like Redux or Flux is helpful?
我应该将状态放到App组件上,还是在Redux或Flux之类的东西有用处?
Home | About | Profile
-----------------------------------
| |
| Content |
...
Top level component: 顶级组件:
function App(props) {
switch (props.location[0]) {
case '':
return <Home />;
case 'about':
return <About />;
case 'profile':
return <Profile />;
default:
return <NoMatch />;
}
}
App.propTypes = {
location: React.PropTypes.array.isRequired,
};
function renderOnHashChange() {
let location = window.location.hash.replace(/^#\/?|\/$/g, '').split('/');
const application = <App location={location} />;
ReactDOM.render(application, document.getElementById('app'));
}
window.addEventListener('hashchange', renderOnHashChange, false);
renderOnHashChange();
The simple answer is that you need to use some kind of store to retain the global state of your app. 简单的答案是,您需要使用某种类型的存储来保留应用程序的全局状态。 It's up to you what you choose;
您的选择取决于您; you've already identified some popular examples but there are more out there.
您已经确定了一些受欢迎的示例,但还有更多示例。 Update the store by dispatching actions.
通过调度操作来更新商店。
I would not recommend adding state to your top-level component, as this would require you to pass callbacks through every layer of application to call setState
. 我不建议将状态添加到顶级组件,因为这将要求您通过应用程序的每一层传递回调以调用
setState
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.