Reactjs 使用react router调用Infinite componentDidUpdate()
我是Reactjs 使用react router调用Infinite componentDidUpdate(),reactjs,react-router,Reactjs,React Router,我是react router新手,现在我的应用程序中有以下路径: <Router history={browserHistory}> <Route path="/" component={MainLayout}> <Route path="/v/:username/:reponame/:page/:perPage" component={Results} /> </Route> </Router> se
react router
新手,现在我的应用程序中有以下路径:
<Router history={browserHistory}>
<Route path="/" component={MainLayout}>
<Route path="/v/:username/:reponame/:page/:perPage" component={Results} />
</Route>
</Router>
sendRequests
基本上包含用于获取输出数据的ajax查询,然后将其设置为组件状态:
this.state = {
data: [], // here
lastPage: -1,
errorMessage: ''
}
现在,直到人们想要更改输入的值时,这种方法仍然非常有效
如我所见,Result
组件不会卸载。相反,它调用组件willreceiveprops()
并更新现有组件。好的,在componentdiddupdate()
中执行边调用是安全的,所以我只是从componentDidMount()
复制了上面的代码并粘贴到那里。但是,通过这种方式(这是绝对合理的)componentDidMount()
被反复调用
目前我提出的唯一解决方法是比较sendRequest()
本身中的新旧数据,只有通过deep equal
包不同时,才在其内部调用setState()
,因此看起来像这样:
if (!equal(res, this.state.data)) {
this.setState({
...this.state,
data: res,
lastPage
});
}
这被认为是一种正常模式,还是有更好的方法来解决这个问题?您不应该在cDM生命周期内使用setState。因为它可能会触发重新渲染,这将导致无限循环
在组件装载后更新状态将触发第二个render()调用,并可能导致属性/布局抖动
如果对两个对象进行字符串化,则可以进行字符串比较,这应该会更快。但是如果您只是比较状态中的数据,那么调用this.setState({data:res})
if (!equal(res, this.state.data)) {
this.setState({
...this.state,
data: res,
lastPage
});
}