【发布时间】: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