【发布时间】:2020-03-01 23:32:33
【问题描述】:
我正在使用 React 和 redux,我有一个场景。我有四个动作,其中一个取决于其他两个。
如果我们有this.props.fetch1()、this.props.fetch2()、this.props.fetch3(),首先我需要接收this.props.fetch1()和this.props.fetch2()的结果,然后使用每个结果的id字段通过redux向服务器发出请求这个:
1.
this.props.fetch1()
this.props.fetch2()
2.
this.props.fetchResult1.id1
this.props.fetchResult2.id2
3.
this.props.fetch3(this.props.fetchResult1.id1, this.props.fetchResult1.id2)
4.
this.props.fetchResult3
5.
show the list on the page
然后通过使用this.props.fetchResult3 这是一个数组,我正在制作一个列表以在渲染页面时显示在页面上。
问题是因为这个动作是异步的,所以结果还没有准备好使用。我使用shouldComponentUpdate 进行渲染,直到结果准备好,但它阻止状态在其他部分更新,即使我比较状态以更新它也会重新渲染组件,在我的情况下,每次更改都会导致我在页面上重置我的字段值处于状态。(我在提交页面上有 2 个文本输入和一个复选框)
shouldComponentUpdate(nextProps, nextState, nextContext) {
return !isEqual(nextProps.fetchResult1, this.props.fetchResult1) ||
!isEqual(nextProps.fetchResult2, this.props.fetchResult2) ||
!isEqual(nextState.fetchResult2, this.state.fetchResult2)
}
componentDidMount() {
this.callfetch1fetch2();
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (prevProps.fetchResult1 === this.props.fetchResult1 && !this.props.fetchResult2) {
this.callfetch1fetch2();
} else {
this.callfetch3();
}
}
我想知道处理这个问题的最佳方法,既可以防止重新渲染,又可以正确更新状态。
提前感谢您的任何建议。
【问题讨论】:
标签: reactjs redux components