简体   繁体   中英

Changing state in array state redux react native

The inital state I have for result list from server will be on result

var InitialState = Record({
   result:[]
})

The result from server is list of search result.

Example array result

[{id:1 ,Bookmark:true},
{id:2 ,Bookmark:true}],
.....

My reducer

case SET_BOOKMARK:
      return state.setIn(['result', 'Bookmark'], action.payload.total)

I want to update the specific bookmark state when user bookmark specific id, How to achive that? How to reducer look like?

Here is an example for your case

const { setIn } = require('immutable@4.0.0-rc.9')

const state = {"results": [{id:1 ,Bookmark:true},
{id:2 ,Bookmark:true}]};

function findElementIndex(arr, key, value) {
  for (let i = 0; i < arr.length; i++)
    if (arr[i][key] === value)
      return i;
}
const newState = setIn(state, 
    ['results', findElementIndex(state.results, 'id', 1), 'Bookmark'], false);

console.log(newState);

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