【问题标题】:reducer A make reducer B undefined (React - Redux)reducer A 使 reducer B 未定义(React - Redux)
【发布时间】:2022-01-01 06:36:15
【问题描述】:

我在一个 combine reducer 中有两个 reducer,当我调用一个动作来更改 reducerSrc 的状态时,我的 reducerTherm 状态变得未定义并且我收到一个错误。我该如何解决这个问题?

结合:

 const rootReducer = combineReducers({
      therm: reducerTherm,
      src: reducerSrc,
    });
    
    export type RootState = ReturnType<typeof rootReducer>;
    
    export const store = createStore(rootReducer);

reducerTherm:

interface Props {
  therm: string;
}

const initialState: Props = {
  therm: "",
};

export default function reducerTherm(state: Props = initialState, action: any) {
  switch (action.type) {
    case "SEARCH_THERM":
      return action.payload;
      break;
    default:
      return state.therm;
  }
}

reducerSrc:

export interface Props {
  src: any;
}

const initialState: Props = {
  src: "source teste",
};

export default function reducerSrc(state: Props = initialState, action: any) {
  switch (action.type) {
    case "ADD_SRC":
      return action.payload;
      break;
    default:
      return state;
  }
}

useEffect 观察 therm 的变化,并通过此活动对 reducerSrc 执行操作:

 const therm = useSelector((state: RootState) => state.therm);
  const src = useSelector((state: RootState) => state.src);

  useEffect(() => {
    if (therm) {
      try {
        getPhotosPlaces("shopping")
          .then((res) => res.json())
          .then((data) => {
            store.dispatch({
              type: "ADD_SRC",
              payload: data,
            });
          });
      } catch (error) {
        console.log(error);
      }
    }
  }, [therm]);

错误:

**Unhandled Rejection (Error): When called with an action of type "ADD_SRC", the slice reducer for key "therm" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.**

【问题讨论】:

    标签: reactjs typescript redux redux-reducers


    【解决方案1】:

    在您的热减速器的默认情况下,您拥有

    return state.therm; // possibly undefined
    

    你的意思是返回reducer状态(不是键therm

    return state; // returns { therm: ... }
    

    【讨论】:

      猜你喜欢
      • 2021-01-02
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 2018-11-08
      • 2021-01-08
      • 2020-07-04
      • 2018-05-27
      • 2016-05-05
      相关资源
      最近更新 更多