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

How does setState in React work in this scenario?

我正在尝试设置数组中对象的状态。我实现了,但是我看不懂

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({}),它仍然有效。我一直认为设置状态是为对象键设置新值。为什么(无论我在这里输入什么),它仍然设置正确吗?

使用 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
        }
    })
}

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

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
}