react setState with dynamic key

后端 未结 1 851
你的背包
你的背包 2020-11-28 15:38

I have the following snippet of code:

onChange(e) {
    e.persist
    this.setState((prevState) => {
      prevState[e.target.id] =  e.target.value
               


        
相关标签:
1条回答
  • 2020-11-28 16:34

    Basic rule is:

    We can use Computed property names concept and use any js expression to compute the object property name dynamically. For that we need to put the expression inside [].

    Like this:

    var obj = {
       [10 * 20 + 1 - 5]: "Hello"
    };
    
    console.log('obj = ', obj);

    Solution:

    As per the code you posted, you need to put e.target.id inside [], like this:

    onChange(e) {
        this.setState({
          [e.target.id]: e.target.value
        })
    }
    

    Or we can create that object first, then pass that object to setState function, like this:

    onChange(e) {
        let obj = {};
        obj[e.target.id] = e.target.value
        this.setState(obj);
    }
    

    Also you don't need the prevState. You can directly update the state variable with new value.prevState is required only when new state value is dependent on previous state value, like in case of counter.

    0 讨论(0)
提交回复
热议问题