如何使用状态更新React

如何使用状态更新React

本文介绍了如何使用状态更新React JS中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我只想更新一个对象的值,但要更新一个对象的值,更新所有对象的值。

I want to update value of one object only but updating value of one Object, Updates the value for all objects.

let default = {
    name: '',
    age: ''
}
this.state = {
    values: Array(2).fill(default)
}

updateName (event) {
    let index = event.target.id,
    values = this.state.values;

    values[index].name = event.target.value;

    this.setState ({
        values: values
    });
}


推荐答案


  1. 您正在对数组中的所有条目使用 same 对象。如果要使用其他对象,则必须创建默认对象的多个副本。

  1. You're using the same object for all entries in your array. If you want to have different objects, you have to create multiple copies of the default.

您要调用 setState 错误。每当您基于现有状态设置状态(并且您直接基于 this.state.values 时) c $ c>),则必须使用 setState 的函数回调版本。更多:

You're calling setState incorrectly. Any time you're setting state based on existing state (and you're setting values based, indirectly, on this.state.values), you must use the function callback version of setState. More: State Updates May Be Asynchronous

您不能直接修改 this.state.values ;相反,您必须对对象进行复制并进行修改。更多:

You can't directly modify the object held in this.state.values; instead, you must make a copy of the object and modify that. More: Do Not Modify State Directly

default 是(即使当前未使用),也不能将其用作标识符。让我们改用 defaultValue

default is a keyword (even though it's not currently used), you can't use it as an identifier. Let's use defaultValue instead.

这是您可以使用的一种方法解决这三个问题(见注释):

Here's one way you can address all three (see comments):

// #4 - `default` is a keyword
let defaultValue = {
    name: '',
    age: ''
};
this.state = {
    // #1 - copy default, don't use it directly
    values: [
        Object.assign({}, defaultValue),
        Object.assign({}, defaultValue)
    ] // <=== Side note - no ; here!
}

updateName (event) {
    let index = event.target.id,
    // #2 - state updates working from current state MUST use
    // the function callback version of setState
    this.setState(prevState => {
        // #3 - don't modify state directly - copy the array...
        values = prevState.values.slice();

        // ...and the object, doing the update
        values[index] = {...values[index], name: event.target.value};

        return {values};
    });
}

请注意上面的这一行:

values[index] = {...values[index], name: event.target.value};

...使用,目前位于Stage4上(将在ES2018快照规范中使用),并且通常在React构建环境中启用。

...uses syntax from this JavaScript enhancement proposal, currently at Stage 4 (it will be in the ES2018 snapshot spec) and commonly enabled in React build environments.

这篇关于如何使用状态更新React JS中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 19:07