在ReactJS中正确修改状态数组

JavaScript

古一达蒙

2020-03-09

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

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

我担心如果就地修改阵列push可能会造成麻烦-是否安全?

制作数组副本的另一种选择setState似乎是浪费的。

第393篇《在ReactJS中正确修改状态数组》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

8个回答
JinJinPro 2020.03.10
this.setState({
  arrayvar: [...this.state.arrayvar, ...newelement]
})
飞云A 2020.03.10
//------------------code is return in typescript 

const updateMyData1 = (rowIndex:any, columnId:any, value:any) => {

    setItems(old => old.map((row, index) => {
        if (index === rowIndex) {
        return Object.assign(Object.assign({}, old[rowIndex]), { [columnId]: value });
    }
    return row;
}));
达蒙樱梅 2020.03.10

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

对于remove元素和array的更新状态,以下代码对我有用。splice(index, 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);
番长猴子古一 2020.03.10

我试图在数组状态中推送值并设置这样的值,并通过map函数定义状态数组并推送值。

 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})
            })
村村老丝 2020.03.10

如评论中提到的@nilgun,您可以使用react 不可变助手我发现这非常有用。

从文档:

简单推

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

initialArray仍为[1、2、3]。

卡卡西Near 2020.03.10

如果使用,最简单ES6

initialArray = [1, 2, 3];

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

新数组将是 [1,2,3,4]

React中更新您的状态

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

了解有关阵列解构的更多信息

伽罗卡卡西 2020.03.10

最简单的方法是ES6

this.setState(prevState => ({
    array: [...prevState.array, newElement]
}))
神乐路易 2020.03.10

阵营的文档说:

将此this.state视为不可变的。

Your push will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards. F.ex, it could lead to that some lifecycle methods like componentDidUpdate won’t trigger.

The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:

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

The memory "waste" is not an issue compared to the errors you might face using non-standard state modifications.

Alternative syntax for earlier React versions

You can use concat to get a clean syntax since it returns a new array:

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

In ES6 you can use the Spread Operator:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android