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

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

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

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


当前回答

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

initialArray = [1, 2, 3];

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

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

在React中更新你的状态

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

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

其他回答

正如@nilgun在评论中提到的,你可以使用react不可变helper。我发现这非常有用。

从文档中可以看出:

简单的推

var initialArray = [1, 2, 3];
var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]

initialArray仍然是[1,2,3]。

对于添加到数组中的新元素,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);

这段代码为我工作:

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

ES6最简单的方法:

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

下面是一个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(', '))
        }

}