-->

How to use object spread with nested properties?

2020-08-14 02:25发布

问题:

I'm trying to return the following in my reducer (react-redux) and it's giving me a syntax error:

return { ...state, loginForm.email: action.payload.email }

state = { loginForm: { email: '', password: '' } } so on

I have babel preset stage 0 installed and es2015. This works fine:

return { ..state, loginForm: action.payload }

回答1:

Error you are getting because of the this key:

loginForm.email

It's not a valid object key.

Write it like this:

return { 
    ...state, 
    loginForm: {
        ...state.loginForm,
        email: action.payload.email
    } 
}


回答2:

I think you want something like this:

{ ...state, loginForm: { email: action.payload.email } }