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

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

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


当前回答

这条准则对我很有用:

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
  this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})

其他回答

这条准则对我很有用:

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
  this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})

用下面的方法可以检查和更新对象

this.setState(prevState => ({
    Chart: this.state.Chart.length !== 0 ? [...prevState.Chart,data[data.length - 1]] : data
}));

功能组件和反应钩子

const [array,setArray] = useState([]);

最后推值:

setArray(oldArray => [...oldArray,newValue] );

在开始时推值:

setArray(oldArray => [newValue,...oldArray] );

在这里,您不能像这样将对象推到状态数组中。你可以用普通数组来推。 这里你需要设置状态,

this.setState({ 
     myArray: [...this.state.myArray, 'new value'] 
})

如果你使用:

const[myArr, setMyArr] = useState([]);

添加:

setMyArr([...myArr, value]);

至于移除:

let index = myArr.indexOf(value);
if(index !== -1)
    setPatch([...myArr.slice(0, index), ...myArr.slice(index, myArr.length-1)]);