简体   繁体   English

State 未使用 Redux 工具包和 Typescript 更新

[英]State not updated using Redux toolkit with Typescript

Using createAsyncThunk and extraReducers, I can get data, but the state isn't updated.使用 createAsyncThunk 和 extraReducers,我可以获得数据,但 state 没有更新。 Here's the code这是代码

// matchMakingSlice.ts
export const getOpenChallenges = createAsyncThunk(
  "openchallenges/get",
  async () => {
    const response = await fetchWrapper<Lobby>("api/p/openchallenges", "GET");
    return response;
  }
);

export const matchMakingSlice = createSlice({
  name: "matchMaking",
  initialState: lobbyState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getOpenChallenges.fulfilled, (state, action) => {
  state = action.payload;
    });
  },
});

export default matchMakingSlice.reducer;

Here I can see the data in the payload, but when I set the state, it doesn't do what I think it would do... Reduc Chrome Addon shows me an empty state.在这里我可以看到有效载荷中的数据,但是当我设置 state 时,它并没有像我认为的那样做...... Reduc Chrome Addon 向我显示了一个空的 state。 I get the same result trying to use a selector in a component.尝试在组件中使用选择器时得到相同的结果。

Here more infos:这里更多信息:

// store.ts
const store = configureStore({
  reducer: {
    matchMaking: mathMakingReducer,
    user: userReducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();

export default store;

// component.ts
const Lobby = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getOpenChallenges());
  }, [dispatch]);

  const challenges = useSelector((state: RootState) => {
    return state.matchMaking.openChallenges;
  });

What I am doing wrong?我做错了什么? Thanks!谢谢!

state = action.payload is never a valid operation in an Immer-powered reducer. state = action.payload在 Immer 驱动的减速器中永远不是有效操作。 Immer works by tracking mutations to existing state , or letting you return a new value. Immer 通过跟踪现有state突变来工作,或者让您返回一个新值。 state = just changes the local state variable to point to something different, which is neither a mutation nor a return. state =只需更改本地state变量以指向不同的东西,这既不是突变也不是返回。 You need return action.payload .您需要return action.payload

See the RTK "Writing Reducers with Immer" docs page for further details on this.有关这方面的更多详细信息,请参阅RTK“使用 Immer 编写减速器”文档页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM