2017-10-28 46 views
0

我需要优化的代码而在设定状态如何阵列更新项目反应

eatMushroom = (foundMushroom, startTime, steps) => { 
    const updatedMushrooms = this.state.mushrooms; 
    updatedMushrooms[foundMushroom.key].remaining = false; 
    this.setState({ 
    mushrooms: updatedMushrooms, 
    score: this.state.score + 1 
    }); 

    if (this.totalMushrooms === this.state.score) { 
    this.props.setTotalTime(startTime, steps); 
    this.props.history.push("/score"); 
    } 
}; 

我这个它采取对性能有收费时,状态更换整个阵列的帮助,而我只是想更新一个单一的项目。

+0

要更新ONY成绩? –

+0

使用传播运算符 –

+0

看看https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs –

回答

2

为了更好的实践,首先应该避免变异状态,如果在更新状态时需要状态值,则应考虑使用功能状态更新。这将有助于始终获得正确的值。

另一个要考虑的是,你正在使用的设置之后this.state.score权。 setState是异步,你做你的if语句之后,可能会发生。为此,您应该考虑使用回调。

下面是与上面的建议,你的代码的修改版本;

this.setState((prevState) => { 
    const mushrooms = Object.assign({}, prevState.mushrooms); 
    mushrooms[foundMushroom.key].remaining = false; 
    return { mushrooms, score: (prevState.score + 1) }; 
},() => { 
    if (this.totalMushrooms === this.state.score) { 
    this.props.setTotalTime(startTime, steps); 
    this.props.history.push("/score"); 
    } 
}); 

我不知道你是如何使用this.state.mushrooms价值,但有更好的表现,你可以做一个小的变化。如果你只想修改一个属性,那么你应该把你的属性上移一层。 mushrooms我认为财产是不必要的。

示例数据

而是然后使用类似下面

this.state = { 
    mushrooms: { 
    mushA: { 
     remaining: true 
    }, 
    mushB: { 
     remaining: false 
    }, 
    mushC: { 
     remaining: true 
    } 
    } 
}; 

您可以使用这样

this.state = { 
    mushA: { 
    remaining: true 
    }, 
    mushB: { 
    remaining: false 
    }, 
    mushC: { 
    remaining: true 
    } 
}; 

这样你就可以更新像下面的状态。一次一个属性,我相信这会导致更好的性能更新。

this.setState((prevState) => { 
    const mushroom = Object.assign({}, prevState[foundMushroom.key], { remaining: false }); 
    return { [foundMushroom.key]: mushroom, score: (prevState.score + 1) }; 
},() => { 
    if (this.totalMushrooms === this.state.score) { 
    this.props.setTotalTime(startTime, steps); 
    this.props.history.push("/score"); 
    } 
});