How to use object spread with nested properties?

喜欢而已 提交于 2020-06-11 17:13:32

问题


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 } }


来源:https://stackoverflow.com/questions/47103028/how-to-use-object-spread-with-nested-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!