有没有办法只改变this.state.first的一部分?假设第三个索引为真,但其余索引保持原样。我不想重写它。我考虑过使用 Spread Sytax,但我不知道该怎么做?
import React from "react";
class MyClass extends React.Component {
constructor() {
super();
this.state = {
first: [false, false, false, false, false, false, false]
};
}
}
最佳答案
我建议您查看 immutability-helper
包(文档:https://github.com/kolodny/immutability-helper),如 https://reactjs.org/docs/update.html 中所述
它将负责确保创建新数组,正如 Chris 在另一个答案中提到的那样。如果没有新数组,状态将不会知道任何更改并且需要更新。在您的情况下,代码看起来像这样:
import React from "react";
import update from "immutability-helper";
class MyClass extends React.Component {
constructor() {
super();
this.state = {
first: [false, false, false, false, false, false, false]
};
}
onChange = (toggleIndex) => {
//gets current value and uses bang (!) operator to get inverse value
let newValue = !this.state.first[toggleIndex];
//immutability-helper will take care of making sure the array gets updated and recreated
let newState = update(this.state, {
first: {
[toggleIndex]: {
$set: newValue
}
}
}
);
this.setState(newState);
}
}
关于javascript - 如何只改变状态的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54335471/