我是新来react-router
和现在我有我的应用程序下面的呼叫路由用于连接到Github API并检索特定回购的问题列表。 。无限componentDidUpdate()与反应路由器
然后在Results
组成步骤下面的代码为它的componentDidMount()
:
componentDidMount() {
const {
username,
reponame,
page,
perPage
} = this.props.params;
this.sendRequest(username, reponame, page, perPage);
}
sendRequests
主要包含AJAX查询用于读取的输出数据,在此之后它被设置到组件的状态:
this.state = {
data: [], // here
lastPage: -1,
errorMessage: ''
}
现在这个工作很好,直到想要改变input
的值。我看到,Result
组件不会卸载。它调用componentWillReceiveProps()
并更新现有组件。 AFAIK在componentDidUpdate()
执行旁路电话是安全的,所以我刚刚从componentDidMount()
复制上面的代码并粘贴在那里。这样,虽然(这是绝对合理的)componentDidMount()
被一遍又一遍地调用。
我此刻想出了唯一的解决方法是在sendRequest()
本身比较新旧数据并调用setState()
它里面只有当它通过deep-equal
包不同,所以它看起来像这样:
if (!equal(res, this.state.data)) {
this.setState({
...this.state,
data: res,
lastPage
});
}
这被认为是一个好的模式,或者有更好的方法来解决这个问题?
你可以做一个字符串比较,如果你既字符串化的对象,这应该会更快。但是如果你只是比较状态中的数据,那么它就足以调用'this.setState({data:res})' – Raulucco