【问题标题】:Change inside key of a state in redux reducer在redux reducer中更改状态的内部键
【发布时间】:2017-11-10 18:59:50
【问题描述】:

我有以下减速器:

   const ListingReducer = (state={
    fetched:false
},action) => {
    if ( action.payload )
    {
        console.log("action.token",action.token);
        console.log("action.payload.profiles",action.payload.profiles);
    }
    switch(action.type)
    {
        case 'SET_LISTING_DATA':
            state = {
                ...state,
                [action.token] : action.payload,
                fetched : true
            }
            break;
        case 'APPEND_LISTING_DATA':
            // console.log("Previous state was: "state[action.token]);
            state[action.token]
             = {
                ...state[action.token],
                profiles : [...state[action.token].profiles,...action.payload.profiles],
                fetched : true
            }
            // console.log("Next state is: "+state[action.token]);

            break;      
    }
    return state;
}

动作:

  1. SET_LISTING_DATA:它将数据设置到键action.token,其中有一个名为profiles的键。
  2. APPEND_LISTING_DATA:它将数据附加到状态键profile

我可以在配置文件键中看到添加的配置文件,但它不会更新视图。

个人资料位于:

state[action.token] ={name:y,data:xy,profiles:[id:x,{},{}],...}

【问题讨论】:

    标签: javascript reactjs redux reducers


    【解决方案1】:

    您似乎需要更改state[action.token],但还要保留以前的状态数据,否则您将始终覆盖您的状态。

    虽然直接改变/改变 state props 不是一个好习惯。

    case 'APPEND_LISTING_DATA':
      return {
        ...state,
        [action.token]: {
           ...state[action.token],
           profiles: [
             ...state[action.token].profiles,
             ...action.payload.profiles,
           ],
           fetched: true,
        }
      }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-28
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2017-11-27
    • 2020-10-21
    • 2021-01-08
    相关资源
    最近更新 更多