在这种情况下,React中的setState如何工作?

时间:2019-01-13 20:59:11

标签: javascript reactjs setstate

我正在尝试在数组中设置对象的状态。我已经实现了,但是我不明白。

toggleVisited = countryCode => {
  var countries = [ ...this.state.countries ];
  var countryToChange = countries.find(country => country.code === countryCode);
  countryToChange.visited = !countryToChange.visited;
  this.setState({ countryToChange });
}

(主要)我了解发生了什么,直到最后this.setState行。

我将代码更改为this.setState({}),但仍然可以使用。我一直认为设置状态是为对象键设置新值。为什么(无论我在这里输入什么),仍然可以正确设置它?

3 个答案:

答案 0 :(得分:2)

使用countryToChange.visited = !countryToChange.visited,您正在更改当前状态。 Don't do this.而是创建一个新对象:

toggleVisited = countryCode => {
    this.setState(prevState => {
        const countries = prevState.countries.map(country => country.code !== countryCode
            ? country
            : {
                ...country,
                visited: !country.visited
            })
        const countryToChange = countries.find(country => country.code === countryCode)

        return {
            countries,
            countryToChange
        }
    })
}

答案 1 :(得分:0)

应将反应组件的状态视为不可变的,但实际上可以更改其值。 您的代码将对您执行的每个setState()均有效,因为setState会触发重新渲染,并且由于您已经更改了状态countryToChange.visited = !countryToChange.visited;,因此该组件将使用新状态重新渲染。

答案 2 :(得分:0)

toggleVisited = countryCode => {
  var countries = [ ...this.state.countries ];
  //here you use spread operator to "clone" all countries
  var countryToChange = countries.find(country => country.code === countryCode);
  //you filter all your countries and get the one with the CC you want
  countryToChange.visited = !countryToChange.visited;
  //your country is an object, and you change visited prop to it's opposite
  //boolean, !false == true
  this.setState({ countryToChange });
  //you just changed your country visited prop, in react you cannot change
  //deep props so, you re-set {countryToChange: countryToChange}
  //or simply {countryToChange} due to new ES features
}