简体   繁体   English

Reactjs 带有动态键名的 setState()?

[英]Reactjs setState() with a dynamic key name?

EDIT: this is a duplicate, see here编辑:这是重复的,请参见此处

I can't find any examples of using a dynamic key name when setting the state. This is what I want to do:在设置 state 时,我找不到任何使用动态密钥名称的示例。这就是我想要做的:

inputChangeHandler : function (event) {
    this.setState( { event.target.id  : event.target.value } );
},

where event.target.id is used as the state key to be updated.其中 event.target.id 用作要更新的 state 密钥。 Is this not possible in React?这在 React 中不可能吗?

Thanks to @Cory's hint, i used this:感谢@Cory 的提示,我使用了这个:

inputChangeHandler : function (event) {
    var stateObject = function() {
      returnObj = {};
      returnObj[this.target.id] = this.target.value;
         return returnObj;
    }.bind(event)();

    this.setState( stateObject );    
},

If using ES6 or the Babel transpiler to transform your JSX code, you can accomplish this with computed property names , too:如果使用 ES6 或Babel 转译器来转换您的 JSX 代码,您也可以使用计算属性名称来完成此操作:

inputChangeHandler : function (event) {
    this.setState({ [event.target.id]: event.target.value });
    // alternatively using template strings for strings
    // this.setState({ [`key${event.target.id}`]: event.target.value });
}

When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.当需要处理多个受控输入元素时,可以给每个元素添加一个name属性,让处理函数根据event.target.name的值来选择要做什么。

For example:例如:

 inputChangeHandler(event) { this.setState({ [event.target.name]: event.target.value }); }

How I accomplished this...我是如何做到这一点的...

inputChangeHandler: function(event) {
  var key = event.target.id
  var val = event.target.value
  var obj  = {}
  obj[key] = val
  this.setState(obj)
},

I just wanted to add, that you can also use de-structuring to refactor the code and make it look neater.我只是想补充一点,您还可以使用解构来重构代码并使其看起来更整洁。

inputChangeHandler: function ({ target: { id, value }) {
    this.setState({ [id]: value });
},

I had a similar problem.我有一个类似的问题。

I wanted to set the state of where the 2nd level key was stored in a variable.我想设置第二级密钥存储在变量中的状态。

eg this.setState({permissions[perm.code]: e.target.checked})例如this.setState({permissions[perm.code]: e.target.checked})

However this isn't valid syntax.但是,这不是有效的语法。

I used the following code to achieve this:我使用以下代码来实现这一点:

this.setState({
  permissions: {
    ...this.state.permissions,
    [perm.code]: e.target.checked
  }
});

In loop with .map work like this:使用.map循环工作是这样的:

{
    dataForm.map(({ id, placeholder, type }) => {
        return <Input
            value={this.state.type}
            onChangeText={(text) => this.setState({ [type]: text })}
            placeholder={placeholder}
            key={id} />
    })
}

Note the [] in type parameter.注意type参数中的[] Hope this helps :)希望这可以帮助 :)

this.setState({ [`${event.target.id}`]: event.target.value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[event.target.id]));
    });

Please mind the quote character.请注意引号字符。

使用 ES6+ 你可以只做 [ ${variable} ]

I was looking for a pretty and simple solution and I found this:我一直在寻找一个漂亮而简单的解决方案,我发现了这个:

this.setState({ [`image${i}`]: image })

Hope this helps希望这可以帮助

when the given element is a object:当给定元素是一个对象时:

handleNewObj = e => {
        const data = e[Object.keys(e)[0]];
        this.setState({
            anykeyofyourstate: {
                ...this.state.anykeyofyourstate,
                [Object.keys(e)[0]]: data
            }
        });
    };

hope it helps someone希望它可以帮助某人

Your state with dictionary update some key without losing other value你的字典状态更新一些键而不会丢失其他值

state = 
{   
    name:"mjpatel"  
    parsedFilter:
    {
      page:2,
      perPage:4,
      totalPages: 50,
    }
}

Solution is below解决方法如下

 let { parsedFilter } = this.state
 this.setState({
      parsedFilter: {
        ...this.state.parsedFilter,
        page: 5
      }
  });

here update value for key "page" with value 5这里更新值为 5 的键“页面”的值

try this one please.请试试这个。

State is here as example State 在这里作为示例

 this.state = {
            name: '',
            surname: '',
            username: '',
            email: '',
  }

Onchange function is here. Onchange function 在这里。

onChangeData = (type, event) => {
    const stateData = this.state;
    if (event === "" || event === "Seçiniz")
        stateData[type] = undefined
    else
        stateData[type] = event

    this.setState({ stateData});
}

Can use a spread syntax, something like this:可以使用扩展语法,如下所示:

inputChangeHandler : function (event) {
    this.setState( { 
        ...this.state,
        [event.target.id]: event.target.value
    } );
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM