我想在状态数组的末尾添加一个元素,这是正确的方法吗?

this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });

我担心用push修改数组可能会导致麻烦——它安全吗?

另一种方法是复制数组,setstate看起来很浪费。


当前回答

//get the value you want to add
const valor1 = event.target.elements.valor1.value;

//add in object 
        const todo = {
            valor1,
        }

//now you just push the new value into the state

//prevlista is the value of the old array before updating, it takes the old array value makes a copy and adds a new value

setValor(prevLista =>{
return prevLista.concat(todo) })
     

其他回答

我试图在数组状态下推值,并像这样设置值,并通过映射函数定义状态数组和推值。

 this.state = {
        createJob: [],
        totalAmount:Number=0
    }


 your_API_JSON_Array.map((_) => {
                this.setState({totalAmount:this.state.totalAmount += _.your_API_JSON.price})
                this.state.createJob.push({ id: _._id, price: _.your_API_JSON.price })
                return this.setState({createJob: this.state.createJob})
            })

这段代码为我工作:

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) => {   
    const newArray = [...prevState.array];   
    newArray[index] = updatedValue;   
    return { array: newArray };   
});
this.setState(preState=>({arrayvar:[...prevState.arrayvar,newelement]}))

这个方法可以解决这个问题。

ES6最简单的方法:

this.setState(prevState => ({
    array: [...prevState.array, newElement]
}))