我有componentWillReceiveProps组件,但是如您所见,我在这里使用了setState 3次。在这种情况下,如何阻止React在任何时候调用“ setState”的情况下渲染?
componentWillReceiveProps = (newProps) => {
let apiDat = newProps.apiDat;
let apiData = newProps.apiData;
if (apiData.activities && apiData.activities.success ) {
let therapists = apiData.activities.therapists;
let hasMore = true;
if (therapists.length < 10) {
hasMore = false;
}
this.setState(() => ({
therapists: this.state.therapists.concat(therapists),
hasMore: hasMore,
pageLoading: false
}))
}
if (apiDat.targets && apiDat.targets.success) {
let globalTargets = apiDat.targets.globals;
let hasMore = true;
if (globalTargets.length < 10) {
hasMore = false;
}
this.setState(() => ({
globalTargets: this.state.globalTargets.concat(globalTargets),
}))
}
if (apiData.followActivities && apiData.followActivities.success) {
let follows = apiData.followActivities.follows;
let hasMore = true;
if (follows.length < 10) {
hasMore = false;
}
this.setState(() => ({
follows: this.state.follows.concat(follows),
}))
}
}
答案 0 :(得分:1)
在每个条件中建立新状态,然后在末尾调用setState
。
const newState = {};
if (foo && bar) {
newState.baz = 1;
}
if (asdf && fdsa) {
newState.blah = 2;
}
this.setState(newState);