【问题标题】:redux-toolkit extraReducers action.playload cant get deep valueredux-toolkit extraReducers action.payload 获取不到深度值
【发布时间】:2023-01-19 16:36:45
【问题描述】:
interface ListMakerResponse {
  result: number;
  detail: string;
  message: string;
  list: Maker[];
}

interface ListMakerRequest {
  dynamic: string;
}

type Maker = {
  makerId: string;
  makerName: string;
};

type OrganazationState = {
  status: "idle" | "loading" | "succeeded" | "failed";
  error: Error | null;
  response: ListMakerResponse;
};

const initialState: OrganazationState = {
  status: "idle",
  error: null,
  response: {} as ListMakerResponse,
};

export const postMakerList = createAsyncThunk(
  "list_maker",
  async (_, { rejectWithValue }) => {
    const response = await http.usePost<ListMakerResponse, ListMakerRequest>(
      "http://localhost:8080/list_maker",
      {
        dynamic: "gravity",
      }
    );
    return response.data;
  }
);

export const OrganazationSlice = createSlice({
  name: "organazation",
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder.addCase(postMakerList.fulfilled, (state, action) => {
      const { message } = action.payload;

      console.log("successed", message);
      state.response = action.payload;
      state.status = "succeeded";
    });
    builder.addCase(postMakerList.rejected, (state, action) => {
      console.log("failed");
      state.status = "failed";
    });
  },
});

export const responseSelect = (state: RootState) => state.organazation.response;

export const messageSelect = createSelector(
  responseSelect,
  (res) => res.message
);

export default OrganazationSlice.reducer;

就像标题一样,action.playload 具有值,但是当我尝试访问 playload 中的嵌套值时,我得到了未定义的值。我想获得部分响应(如消息或列表)并显示 在 html 上我该怎么做。

我正在使用 useEffect 来发送 postMakerList

 const dispatch = useAppDispatch();

  const response = useAppSelector(responseSelect);
  const message = useAppSelector(messageSelect);

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

事实上,当我使用 response 时,它​​会显示在 html 中,但是当我使用 message 或 response.message 时 不要出现。

【问题讨论】:

  • 尝试将代码添加到沙箱并共享链接

标签: reactjs next.js react-redux redux-toolkit


【解决方案1】:

我已经解决了问题 我的代码没有问题 问题是我使用 mockoon 作为 存根,它返回字符串而不是对象。

【讨论】:

  • 如果您提供有效的 JSON,Mockoon 应该返回 JSON 并让您使用数组/对象。如果您在设置模拟时需要任何具体帮助,请毫不犹豫地加入我们的 Discord。我们很乐意提供帮助!
猜你喜欢
  • 1970-01-01
  • 2020-08-28
  • 2021-09-11
  • 2023-04-09
  • 2022-12-11
  • 2021-04-23
  • 2021-11-01
  • 2020-06-11
  • 1970-01-01
相关资源
最近更新 更多