React Router 4 与 Mobx 重新初始化组件
React Router 4 with Mobx reinitializes component
我正在使用 react router v4 和 mobx,我 运行 遇到了一个非常烦人的错误。
这是我的 index.js
const history = createHashHistory();
render(
<Provider history={history} {...stores}>
<Router history={history}>
<Application />
</Router>
</Provider>, document.getElementById('root')
)
在应用程序内部,我有一个带有导航链接的菜单组件和一个主体,其中我有一个开关
<Switch>
<Route path='/somecomponent/' exact={true} component={SomeComponent} />
{ other routes>}
</Switch>
Application和Body都用@withRouter修饰,所以路由可以正常工作,但是
每次我导航到“/somecomponent”时,都会创建一个新的 SomeComponent 实例。
这是 SomeComponent 的构造函数:
class SomeComponent extends React.Component {
constructor(props){
super(props);
this.store = new SomeComponentStore();
console.log('reinitialising')
}
是的,console.log 运行s 每次我去那条路线时也会创建一个新商店(这就是我最初注意到问题的方式)。该 Switch 内的所有其他组件的行为方式相同。
任何人都可以向我解释导致问题的原因以及解决方法吗?
React Router 组件在不活动时(即路由不匹配)不会呈现各个路由,这会导致它们被卸载并且实例被销毁。当它们再次活跃时,它们需要被重建。如果你在 React Devtools 中查看这个组件,你会看到组件完全消失了。
这是预期的行为,您在设计组件层次结构时应牢记这一点。例如,如果您想跨路由更改维护应用程序状态,则将上面的状态存储移动到实例不受路由器管理的组件,并将其作为道具向下传递。
我正在使用 react router v4 和 mobx,我 运行 遇到了一个非常烦人的错误。 这是我的 index.js
const history = createHashHistory();
render(
<Provider history={history} {...stores}>
<Router history={history}>
<Application />
</Router>
</Provider>, document.getElementById('root')
)
在应用程序内部,我有一个带有导航链接的菜单组件和一个主体,其中我有一个开关
<Switch>
<Route path='/somecomponent/' exact={true} component={SomeComponent} />
{ other routes>}
</Switch>
Application和Body都用@withRouter修饰,所以路由可以正常工作,但是 每次我导航到“/somecomponent”时,都会创建一个新的 SomeComponent 实例。 这是 SomeComponent 的构造函数:
class SomeComponent extends React.Component {
constructor(props){
super(props);
this.store = new SomeComponentStore();
console.log('reinitialising')
}
是的,console.log 运行s 每次我去那条路线时也会创建一个新商店(这就是我最初注意到问题的方式)。该 Switch 内的所有其他组件的行为方式相同。 任何人都可以向我解释导致问题的原因以及解决方法吗?
React Router 组件在不活动时(即路由不匹配)不会呈现各个路由,这会导致它们被卸载并且实例被销毁。当它们再次活跃时,它们需要被重建。如果你在 React Devtools 中查看这个组件,你会看到组件完全消失了。
这是预期的行为,您在设计组件层次结构时应牢记这一点。例如,如果您想跨路由更改维护应用程序状态,则将上面的状态存储移动到实例不受路由器管理的组件,并将其作为道具向下传递。