在我的顶级组件中,我有一个更新状态的功能。我把它传递给不同的子元素,以便他们可以更新我的主要状态。
在我的顶级组件中:
updateValue(item, value) {
this.setState({[item]: parseInt(value)});
}
到目前为止这已经奏效但是现在我需要更新数组中的第n项。
我的顶级州是这样的:
this.state = {
chosenExercises: [
'Bench press',
'Squat',
'Pull up'
]
};
在我的孩子组件中我尝试做类似的事情:
this.props.updateValue('chosenExercises'[1], 'New exercise');
那么我的状态就是:
this.state = {
chosenExercises: [
'Bench press',
'New exercise',
'Pull up'
]
};
我是否以正确的方式进行此操作?或者我的州应该是关键值对吗?
this.state = {
chosenExercises: {
0: 'Bench press',
1: 'New exercise',
2: 'Pull up'
}
};
这可能会解决我使练习更容易定位的一些问题,但我不确定哪种是最佳做法。
答案 0 :(得分:0)
由于selectedExercises可以是多个,因此将它作为一个数组是有意义的,但是你需要以不同的方式更新你的状态。您应该实际制作数组的副本,在子元素中更新它,然后将更新的数组发送给父元素,而不是传递数组元素的索引进行更新。
您可以执行以下操作:
在孩子:
updateValue = (item, index, value) => {
let newValue = [...this.props[item].slice(0, index), value, ...this.props[item].slice(index + 1)];
this.props.updateValue(item, newValue);
}
答案 1 :(得分:0)
这个问题是你的状态必须保持不变,所以你必须提供一个新的数组来更新你的状态。所以你最终得到的结论是:
this.updateValue('chosenExercises', 1, 'New exercise');
updateValue(item, index, value) {
const newArray = this.state[item].slice();
newArray[index] = value;
this.setState({ [item]: newArray });
}
array.slice()
函数创建一个新数组,您可以在其中通过索引更新值。然后使用新阵列更新组件状态。
如果您碰巧经常这样做,React会为这些事情创建一个不变的助手。您可以阅读更多相关信息here。这可以让你做类似的事情:
import update from 'react-addons-update';
this.setState({
[item]: update(this.state[item], {[index]: {$set: value } })
});
答案 2 :(得分:0)
可以在顶级组件中完成此操作:
updateValue(item, value, options) {
if (options.isChosenExercises === true) {
this.setState((prevState) => {
let newchosenExercises = prevState.chosenExercises.slice();
newchosenExercises[item] = value;
return {chosenExercises: newchosenExercises};
});
} else {
this.setState({[item]: parseInt(value)});
}
}
对于正常使用,将空对象作为最后一个参数传递:
this.props.updateValue('setLength', e.target.value, {})}
但是当你想更新训练数组时,传递一个isExercises设置为true的对象。
chooseThisExercise() {
this.props.updateValue(numberInTheArrayToChange, newExercise, {isChosenExercises: true});
}