【发布时间】:2018-09-05 10:47:20
【问题描述】:
我正在使用带有 mobx 的 react router v4,我遇到了一个非常烦人的错误。 这是我的 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 每次我去那条路线时都会运行,并且也会创建一个新商店(这就是我最初注意到问题的方式)。该 Switch 内的所有其他组件的行为方式相同。 谁能给我解释一下是什么导致了这个问题以及如何解决它?
【问题讨论】:
标签: javascript reactjs react-router mobx mobx-react