简体   繁体   中英

Spread Operator with Dynamic Property Keys and nested data?

I have a state object that has a few nested objects. I'd like to update those nested objects in a dynamic way so i'm not copying and pasting the same logic with slight tweeks in different cases. Here's an example of a case in my reducer.

case UPDATE_MESSAGE_FORM:{
  const {id, data} = action.payload
  const key = id.toLowerCase()
    return {
      ...state,
      form: {
        ...state.form
        [key]: {
          // this must be incorrect or not possible 
          ...state.form.key,
          message: data
        }
      }
    }
  }

Currently that works and I get the message to store in the state object, but if I run that again with another key or even in a different case that is supposed to update another field in that nested object it returns the object with just that field. Can you dynamically spread with a nested object?

There is something you are doing wrong there. You are assigning the value and not the key of id to the key inside form: {...}. Given id = "123dfs2" and state.form.id = "abc" your output would look like:

form: {
 [123dfs2]: {
   0: "a",
   1: "b",
   2: "c"
 }
}

  1. You are using the value of id as a key for the id property in form and I assume you want it to be form.id
  2. you are destructuring a string, state.form.id and when you do that the output will be each letter in that string

Yes, you can achieve what you asked, but it is a bit more complicated and also dangerous as you are mutating state with no control to what it is going to be dumped into it. This results into unexpected behaviour and errors.

As a practice it is recommended to always know what you expect from a payload and use it specifically in the reducer. Let me know if you want more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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