简体   繁体   中英

update the array of object in the react redux

I am new to the react-redux .

const initialState = {
    Low: [
        {
            id: 0,
            type: '',
            count: '',
            allowded: 6,
            level: 'EASY'
        }
    ],
    Medium: [
        {
            id: 0,
            type: '',
            count: '',
            allowded: 7,
            level: 'MEDIUM'
        }
    ],
    High: [
        {
            id: 0,
            type: '',
            count: '',
            allowded: 7,
            level: 'TOUGH'
        }
    ]
}

This is my initial state value.

After that ,

onChange(event, tobeupdated, id, type, noc, data) {
   let newData = { ...this.props.data };
    if (newData) {
      let data = newData[type].map((object, index) => {
        if (object.id === id) {
          object[tobeupdated] = event.target.value;
          const tobeData = newData[type];
         this.props.updateLowLevel({tobeData, type}).then(() => {
            let criteria_filled = this.disableAddbutton({ ...this.props.data }, type);
            addedRow = `new${type}RowAdded`;
            this.setState({
              [addedRow]: criteria_filled ? true : false
            })
});
}

This way I am updating the object values. and then replacing that whole object.

return (dispatch) => {
    dispatch({
      type: QUIZ_DATA,
      data: tobeUpdated,
    });
    return Promise.resolve();
  }
}

In my reducer ,

case QUIZ_DATA:
            return {
                ...state,
                [action.data.type]: [action.data.tobeData],
                error: false,
            }

Now,Here what is happening when I change the lets say type then it adds that array of object to as a children to the previous array. so, it gets added as many as you are adding. SO, because of that I am not able to get that render properly.

So what Happens is , Low : 在此处输入图片说明

This way gets added. So, How Can I do this ?

Can any one helm me with this ?

Try this out as a reducer. It spreads the content of tobeData to an array.

case QUIZ_DATA:
            return {
                ...state,
                [action.data.type]: [...action.data.tobeData], // the difference is here
                error: false,
            }
[action.data.type]: [...action.data.tobeData],

The data you passing through action.data.tobeData (eg: [1,2,3]) is the array itself.

So when you use [action.data.type]: [action.data.tobeData] , this will create the array of array [[1, 2, 3]] .

You could use [action.data.type]: [...action.data.tobeData] , this is called spread operator, all it's doing is basically copy all the element inside action.data.tobeData and spread it out.

You can refer to this document Spread syntax

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