使用dispatch更改数组的特定值

时间:2019-12-11 21:14:22

标签: javascript reactjs

我正在浏览页面上,我想将islLiked的值从true更改为false,或者相反地取决于为用户提供ID的onClick


//this is how i set the result into state
{ ...state, browser: { ...state.browser, result: payload } };

这是我的状态enter image description here

这是我的减速机

export const profileInitState = {
  photo: {
    loading: true,
    profile_Image: "",
    cover_Image: "",
    first_Image: "",
    second_Image: "",
    third_Image: "",
    fourth_Image: ""
  },
  info: {
    loading: true,
    liked: false,
    matched: false,
    blocked: false,
    id: "",
    user_first_name: "",
    user_last_name: "",
    user_gender: "",
    user_relationship: "",
    user_birth_day: "",
    user_birth_month: "",
    user_gender_interest: "",
    user_birth_year: "",
    user_age: "",
    user_tags: "",
    user_city: "",
    user_current_occupancy: "",
    user_biography: "",
    user_set_from_map: null,
    user_fame_rate: 0,
    user_location: {
      lat: "",
      lng: ""
    }
  },
  browser: {
    result: [],
    sort_by: ""
  }
};

export const profileReducer = (state, action) => {
  const { type, payload } = action;
  switch (type) {
    case PHOTO_SUCCESS:
      return { ...state, photo: payload };
    case INFO_SUCCESS:
      return { ...state, info: payload };
    case PROFILE_BLOCKED:
      return { ...state, info: { ...state.info, blocked: payload } };
    case PROFILE_LIKED:
      return { ...state, info: { ...state.info, liked: payload } };
    case PROFILE_MATCHED:
      return { ...state, info: { ...state.info, matched: payload } };
    case BROWSER_RETURN:
      return { ...state, browser: { ...state.browser, result: payload } };
    case SET_NEW_ISLIK:
    // i want to keep the previouse result and change only the value of islike with the value of payload but just for the chossen user with the same id it will also be on payload: {
        //isLike: res.fromdb,
        //valide: id
      //}
    case SORT_BY_BACK:
      return { ...state, browser: { ...state.browser, sort_by: payload } };
    default:
      return state;
  }
};

isLike的新值将在有效负载上

我想知道是否有一种方法可以在用户ID的帮助下完成,希望您能得到我想解释的内容

1 个答案:

答案 0 :(得分:1)

应该这样做:

case SET_NEW_ISLIK:
  return {
    ...state,
    browser: {
      ...state.browser,
      result: state.browser.result.map(user => (
        user.id === payload.userId
        ? { ...user, isLiked: payload.isLiked }
        : user )
      )
    }
  }