出于某种原因与简单的setState进行斗争。
this.state = {
dancers: [{name: "Dancer1", score1: 10, score2: 8, score3: 7, totalScore: 0},
{name: "Dancer2", score1: 5, score2: 7, score3: 8, totalScore: 0},
{name: "Dancer3", score1: 6, score2: 6, score3: 7, totalScore: 0},
{name: "Dancer4", score1: 9, score2: 5, score3: 6, totalScore: 0},
{name: "Dancer5", score1: 8, score2: 8, score3: 7, totalScore: 0},
{name: "Dancer6", score1: 10, score2: 9, score3: 10, totalScore: 0},
{name: "Dancer7", score1: 6, score2: 10, score3: 9, totalScore: 0},
{name: "Dancer8", score1: 8, score2: 4, score3: 6, totalScore: 0},]
}
}
calculateScore() {
const dancers = this.state.dancers;
dancers.map(dancer => {
return this.setState({dancer, totalScore: 10});
})
}
<Link to={{ pathname: "/top8" }} ><button className="create-button" onClick={() => this.calculateScore()}>Make Top 8</button></Link>
现在,我只想了解为什么totalScore不能更新。
答案 0 :(得分:1)
您不应修改状态以对现有状态进行一些计算。如果可能,请从您的州推导值,如下所示:
Dancers
一个更好的解决方案是为单个舞者渲染一个单独的组件,并在那里计算总得分。这更符合React的最佳实践,在该最佳实践中,每个组件只能做一件事。
因此,您将拥有一个Dancer
组件来处理舞者数组,然后呈现多个pyspellchecker
组件,每个组件都基于自己的本地道具计算总店面。
答案 1 :(得分:1)
在执行this.setState({dancer, totalScore: 10});
时,它会以如下所示的状态创建dancer
this.state = {
dancers: [{name: "Dancer1", score1: 10, score2: 8, score3: 7, totalScore: 0},
{name: "Dancer2", score1: 5, score2: 7, score3: 8, totalScore: 0},
{name: "Dancer3", score1: 6, score2: 6, score3: 7, totalScore: 0},
{name: "Dancer4", score1: 9, score2: 5, score3: 6, totalScore: 0},
{name: "Dancer5", score1: 8, score2: 8, score3: 7, totalScore: 0},
{name: "Dancer6", score1: 10, score2: 9, score3: 10, totalScore: 0},
{name: "Dancer7", score1: 6, score2: 10, score3: 9, totalScore: 0},
{name: "Dancer8", score1: 8, score2: 4, score3: 6, totalScore: 0},]
dancer: {name: "Dancer8", score1: 8, score2: 4, score3: 6, totalScore: 0},
totalScore: 10,
}
所以您应该像下面这样
const calculatedDancers = dancers.map(dancer => {
return { ...dancer, totalScore: 10 }
})
this.setState({ dancers: calculatedDancers })