我似乎有问题将数据推入一个状态数组。 我正试图以这种方式实现它:

this.setState({ myArray: this.state.myArray.push('new value') })

但我相信这是不正确的方式,并导致问题的可变性?


当前回答

使用es6可以这样做:

this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array

传播的语法

其他回答

你破坏了React的原则,你应该克隆旧的状态,然后将其与新数据合并,你不应该直接操纵你的状态, 你的代码应该是这样的

fetch (http://localhost: 8080”)。然后(response => response.json)。然后(json ={这个setState ({mystate ...这个state university)。我的状态,杰森]

这条准则对我很有用:

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
  this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})
  setState([...prevState, {
    label: newState.name,
    value: newState.id
  }]);

正在与下拉菜单工作,并希望在那里实现这个场景,我发现了这个简单的解决方案下拉多个值。

你根本不应该管理这个国家。至少,不是直接的。如果你想要更新你的数组,你会想要这样做。

var newStateArray = this.state.myArray.slice();
newStateArray.push('new value');
this.setState(myArray: newStateArray);

直接处理状态对象是不可取的。你也可以看看React的不可变性帮助。

https://facebook.github.io/react/docs/update.html

使用react钩子,你可以这样做

const [countryList, setCountries] = useState([]);


setCountries((countryList) => [
        ...countryList,
        "India",
      ]);