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

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

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

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


当前回答

如果你在React中使用功能组件

const [cars, setCars] = useState([{
  name: 'Audi',
  type: 'sedan'
}, {
  name: 'BMW',
  type: 'sedan'
}])

...

const newCar = {
  name: 'Benz',
  type: 'sedan'
}

const updatedCarsArray = [...cars, newCar];

setCars(updatedCarsArray);

其他回答

目前很多人都面临着更新useState钩子状态的问题。我使用这种方法来安全地更新它,并想在这里分享它。

这就是我的状态

const [state, setState] = useState([])

假设我有一个对象名为obj1,我想把它附加到我的状态中。我建议这样做

setState(prevState => [...prevState, obj1])

这将安全地在末尾插入对象,并保持状态一致性

对于添加到数组中的新元素,push()应该是答案。

对于删除元素和更新数组的状态,下面的代码适用于我。拼接(索引,1)不能工作。

const [arrayState, setArrayState] = React.useState<any[]>([]);
...

// index is the index for the element you want to remove
const newArrayState = arrayState.filter((value, theIndex) => {return index !== theIndex});
setArrayState(newArrayState);

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'));

如果使用ES6,这是最简单的方法。

initialArray = [1, 2, 3];

newArray = [ ...initialArray, 4 ]; // --> [1,2,3,4]

新数组为[1,2,3,4]

在React中更新你的状态

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

了解关于数组解构的更多信息