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

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

其他回答

我所做的是在状态之外更新一个值,并执行forceupdate(),由react管理的东西越少越好,因为您可以更好地控制更新的内容。 此外,如果更新速度很快,为每次更新创建一个新数组可能代价太大

ES6最简单的方法:

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

React可以批处理更新,因此正确的方法是为setState提供一个执行更新的函数。

对于React更新插件,以下将可靠地工作:

this.setState( state => update(state, {array: {$push: [4]}}) );

或者对于concat():

this.setState( state => ({
    array: state.array.concat([4])
}));

下面以https://jsbin.com/mofekakuqi/7/edit?js,output为例说明如果您弄错了会发生什么。

setTimeout()调用正确地添加了三个项,因为React不会在setTimeout回调中批量更新(参见https://groups.google.com/d/msg/reactjs/G6pljvpTGX0/0ihYw2zK9dEJ)。

错误onClick只会添加“第三”,但固定的一个,将添加F, S和T如预期。

class List extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      array: []
    }

    setTimeout(this.addSome, 500);
  }

  addSome = () => {
      this.setState(
        update(this.state, {array: {$push: ["First"]}}));
      this.setState(
        update(this.state, {array: {$push: ["Second"]}}));
      this.setState(
        update(this.state, {array: {$push: ["Third"]}}));
    };

  addSomeFixed = () => {
      this.setState( state => 
        update(state, {array: {$push: ["F"]}}));
      this.setState( state => 
        update(state, {array: {$push: ["S"]}}));
      this.setState( state => 
        update(state, {array: {$push: ["T"]}}));
    };



  render() {

    const list = this.state.array.map((item, i) => {
      return <li key={i}>{item}</li>
    });
       console.log(this.state);

    return (
      <div className='list'>
        <button onClick={this.addSome}>add three</button>
        <button onClick={this.addSomeFixed}>add three (fixed)</button>
        <ul>
        {list}
        </ul>
      </div>
    );
  }
};


ReactDOM.render(<List />, document.getElementById('app'));

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

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

React文档说:

对待这个问题。状态,仿佛它是不可变的。

您的推送将直接改变状态,这可能会导致容易出错的代码,即使您随后再次“重置”状态。例如,它可能导致一些生命周期方法(如componentDidUpdate)无法触发。

在以后的React版本中,推荐的方法是在修改状态时使用updater函数来防止竞争条件:

this.setState(prevState => ({
  arrayvar: [...prevState.arrayvar, newelement]
}))

与使用非标准状态修改可能面临的错误相比,内存“浪费”不是一个问题。

早期React版本的替代语法

你可以使用concat来获得一个干净的语法,因为它返回一个新数组:

this.setState({ 
  arrayvar: this.state.arrayvar.concat([newelement])
})

在ES6中,你可以使用扩展操作符:

this.setState({
  arrayvar: [...this.state.arrayvar, newelement]
})