Javascript 使用Mobx重新初始化组件来响应路由器4
我将react router v4与mobx一起使用,我遇到了一个非常恼人的bug。 这是我的index.jsJavascript 使用Mobx重新初始化组件来响应路由器4,javascript,reactjs,react-router,mobx,mobx-react,Javascript,Reactjs,React Router,Mobx,Mobx React,我将react router v4与mobx一起使用,我遇到了一个非常恼人的bug。 这是我的index.js const history = createHashHistory(); render( <Provider history={history} {...stores}> <Router history={history}> <Application />
const history = createHashHistory();
render(
<Provider history={history} {...stores}>
<Router history={history}>
<Application />
</Router>
</Provider>, document.getElementById('root')
)
是的,console.log每次我去那条路线时都会运行,并且会创建一个新的商店,这就是我最初注意到问题的方式。该开关内的所有其他组件的行为方式相同。
任何人都可以向我解释导致问题的原因以及如何解决问题吗?React路由器组件在各个路由不活动时不呈现它们,即路由不匹配,这会导致它们卸载并销毁实例。当它们再次激活时,需要重建它们。如果在React Devtools中查看此组件,您将看到这些组件完全消失
这是预期的行为,您应该在设计组件层次结构时牢记这一点。例如,如果您希望在路由更改过程中保持应用程序状态,请将状态存储移到上面的某个组件上,该组件的实例不受路由器管理,并将其作为道具传递下去。感谢您提供的详细答案!在谷歌搜索我的问题并找到几个例子后,我真的很困惑,在这些例子中组件没有卸载和重新装载,但现在我看到这些是不同的情况-大多数情况下,只有一个组件具有不同的道具,用于不同的路线。现在这一切对我来说更有意义了,再次感谢!
<Switch>
<Route path='/somecomponent/' exact={true} component={SomeComponent} />
{ other routes>}
</Switch>
class SomeComponent extends React.Component {
constructor(props){
super(props);
this.store = new SomeComponentStore();
console.log('reinitialising')
}