Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

reactjs - Redux change a reducer of type object

So I have the following reducer

const objectType = (state = {type: 0, image:defaultImage, moreOptions: {tap: 0, griff: 0} },
    action) => {....

case 'CHANG_OPTIONS':
      return state = {...state, moreOptions: {tap:action.tap, griff: action.griff}}

This is the action, so I get a dynamic category and assign the id of the product.

export const changeOptions = (category, id) => {
    return {
        type: 'CHANG_OPTIONS',
        [category]: id,
    }
}

An example of dispatch would be

dispatch(changeOptions('tap', 0))

Now whenever I click on a tap or a griff, my object remove the other category from the list.

Here is a screenshot from the Redux Debugger tool

enter image description here

I'm sure that the problem is in my reducer: moreOptions: {tap:action.tap, griff: action.griff} Is there a way I can spread the object and update only the one that was changed?

question from:https://stackoverflow.com/questions/65857577/redux-change-a-reducer-of-type-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's because you're overwritting both tap and griff value regardless of their input value. Try below.

const newOptions = {};
if (action.tap) {
  newOptions.tap = action.tap;
}
if (action.griff) {
  newOptions.griff = action.griff;
}
return (state = {
  ...state,
  moreOptions: {
    ...state.moreOptions,
    ...newOptions
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...