如何在reactjs中更新数组的状态

时间:2017-06-18 13:37:38

标签: reactjs

我有这个按钮可见性的数组。我正在保存状态中这些按钮的状态。

this.state = {
  score: 0,
  status: "",
  userSelected: "",
  computerSelected: "",
  visibility: [true, true, true]
};

我想明智地更新可见性数组的值。我试着像下面这样做,但它没有更新,它不断在数组中添加新元素而不是数组的更新值。

var arrayvar = this.state.visibility.slice();
if (
  (user === "Rock" && computer === "Paper") ||
  (user === "Paper" && computer === "Rock")
) {
  arrayvar.push(true, true, false); // here set 1st and 2nd to true and 3rd to false
} else if (
  (user === "Rock" && computer === "Scissors") ||
  (user === "Scissors" || computer === "Rock")
) {
  arrayvar.push(true, false, true);
} else if (
  (user === "Paper" && computer === "Scissors") ||
  (user === "Scissors" || computer === "Paper")
) {
  arrayvar.push(false, true, true);
} else if (user === "Rock" && computer === "Rock") {
  arrayvar.push(true, false, false);
} else if (user === "Paper" && computer === "Paper") {
  arrayvar.push(false, true, false);
} else if (user === "Scissors" && computer === "Scissors") {
  arrayvar.push(false, false, true);
}
this.setState({ visibility: arrayvar });

有人可以建议如何在reactjs中执行此操作吗?

2 个答案:

答案 0 :(得分:1)

array.push将始终在array中推送新值,但不会更新现有值。

你需要这样写:

arrayvar = [];                     //create a variable, don't need to copy the state values here


arrayvar = [true, true, false];    // assign new array inside conditions

this.setState({
    visibility: arrayvar           //then update the state visibility array
})

您无需创建state array的副本,因为您要更新整个array而不是array的特定值,只需创建一个变量:

arrayvar = [];

完整代码:

var arrayvar = [];
if ( (user === "Rock" && computer === "Paper") || (user === "Paper" && computer === "Rock")) {
    arrayvar = [true, true, false];
} else if ((user === "Rock" && computer === "Scissors") || (user === "Scissors" || computer === "Rock")) {
    arrayvar = [true, false, true]
} else if ((user === "Paper" && computer === "Scissors") || (user === "Scissors" || computer === "Paper")) {
    arrayvar = [false, true, true];
} else if (user === "Rock" && computer === "Rock") {
    arrayvar = [true, false, false];
} else if (user === "Paper" && computer === "Paper") {
  arrayvar = [false, true, false];
} else if (user === "Scissors" && computer === "Scissors") {
  arrayvar = [false, false, true];
}
this.setState({ visibility: arrayvar });

答案 1 :(得分:1)

顺便说一下,

var arrayvar = ["Rock", "Paper", "Scissors"]
    .map(
        k => computer === k || user === k
    );

可以很好地取代你写的整个if-then级联。