Javascript 在reactjs中更新状态索引时出现问题

Javascript 在reactjs中更新状态索引时出现问题,javascript,reactjs,Javascript,Reactjs,我需要更新x属性中foo的索引2。但是使用setState.how i can this?您可以执行以下操作,这将避免对第三方库的需要,同时在状态更新中保持不变性: this.state = {foo : [{x:20,y:40},{x:55,y:10},{x:8,y:90},{x:0,y:150}]};//state this.state.foo[2].x = 80;//change state 很好,但是您需要将{…item}括在括号中。 // Clone the foo list fro

我需要更新x属性中foo的索引2。但是使用setState.how i can this?

您可以执行以下操作,这将避免对第三方库的需要,同时在状态更新中保持不变性:

this.state = {foo : [{x:20,y:40},{x:55,y:10},{x:8,y:90},{x:0,y:150}]};//state
this.state.foo[2].x = 80;//change state

很好,但是您需要将
{…item}
括在括号中。
// Clone the foo list from state
const foo = this.state.foo.map(item => ({ ...item }));

// Update element in cloned list
foo[2].x = 80;

// Update state with cloned list
this.setState({ foo });