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

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

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

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


当前回答

下面是一个2020年的Reactjs Hook示例,我认为它可以帮助其他人。我用它来添加新的行到一个Reactjs表。如果有需要改进的地方,请告诉我。

向功能状态组件添加新元素:

定义状态数据:

    const [data, setData] = useState([
        { id: 1, name: 'John', age: 16 },
        { id: 2, name: 'Jane', age: 22 },
        { id: 3, name: 'Josh', age: 21 }
    ]);

有一个按钮触发一个函数来添加一个新元素

<Button
    // pass the current state data to the handleAdd function so we can append to it.
    onClick={() => handleAdd(data)}>
    Add a row
</Button>
function handleAdd(currentData) {

        // return last data array element
        let lastDataObject = currentTableData[currentTableData.length - 1]

        // assign last elements ID to a variable.
        let lastID = Object.values(lastDataObject)[0] 

        // build a new element with a new ID based off the last element in the array
        let newDataElement = {
            id: lastID + 1,
            name: 'Jill',
            age: 55,
        }

        // build a new state object 
        const newStateData = [...currentData, newDataElement ]

        // update the state
        setData(newStateData);

        // print newly updated state
        for (const element of newStateData) {
            console.log('New Data: ' + Object.values(element).join(', '))
        }

}

其他回答

这对我来说很有用,可以在数组中添加一个数组

this.setState(prevState => ({
    component: prevState.component.concat(new Array(['new', 'new']))
}));

ES6最简单的方法:

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

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

这段代码为我工作:

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

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

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