0
现在我有三种主要组件,一种标头布局在顶部,其中哪一个是活动的,在顶层应用程序组件中用一个非常简单的哈希路由器进行控制。如何保留装载和卸载的React组件的状态?
现在,如果我在Profile组件中设置了一个状态,如果我切换到其他组件之一,状态将被抛出。
我该如何预防?我应该把状态放在应用程序组件上,还是像Redux或Flux那样有帮助?
Home | About | Profile
-----------------------------------
| |
| Content |
...
顶级组件:
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();
'这是像Redux或Flux这样的东西有帮助吗?'是的。 – Aprillion