如何为redux-toolkit实现自己的selectedId?

yyyllmsg  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(176)

我使用redux来获取一些数据,使用这个API "https://valorant-api.com/v1/agents"。问题是我不能显示所有的代理,只有1个出现,我从redux得到警告说:
从selectId传递的实体返回undefined,您可能应该实现自己的selectId函数

我想我的valorantSlice有错误。
我试着这样显示代理列表
(in这个API我想展示的细节太)

export const fetchValorants = createAsyncThunk(
  "valorants/fetchValorants",
  async () => {
    const response = await axios
      .get("https://valorant-api.com/v1/agents")
      .then((response) => response.data.data)
      .then((agents) => {
        return Promise.all(
          agents.map((agent: any) =>
            axios.get(`https://valorant-api.com/v1/agents/${agent.uuid}`)
          )
        );
      })
      .then((agentDetails) => {
        return agentDetails.map((response) => response.data.data);
      });

    return response;
  }
);

这是我的那一片

const valorantAdapter = createEntityAdapter();

const initialState = valorantAdapter.getInitialState({
  status: "idle",
  error: "" as any,
});

export const fetchValorants = createAsyncThunk(
  "valorants/fetchValorants",
  async () => {
    const response = await axios
      .get("https://valorant-api.com/v1/agents")
      .then((response) => response.data.data)
      .then((agents) => {
        return Promise.all(
          agents.map((agent: any) =>
            axios.get(`https://valorant-api.com/v1/agents/${agent.uuid}`)
          )
        );
      })
      .then((agentDetails) => {
        return agentDetails.map((response) => response.data.data);
      });

    return response;
  }
);

const valorantsSlice = createSlice({
  name: "valorants",
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchValorants.pending, (state, action) => {
        state.status = "loading";
      })
      .addCase(fetchValorants.fulfilled, (state, action) => {
        state.status = "succeeded";
        action.payload.forEach((agent) => {
          valorantAdapter.addOne(state, agent);
        });
      })
      .addCase(fetchValorants.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.error.message;
      });
  },
});

export default valorantsSlice.reducer;
export const {
  selectAll: selectAllValorants,
  selectById: selectValorantByUuid,
  selectIds: selectValorantUuids,
} = valorantAdapter.getSelectors((state: any) => state.valorants) as any;

我在nextjs 13中使用react-redux
redux devtools截图

mwkjh3gx

mwkjh3gx1#

实体键下的undefined让我认为Valorant API的响应不具有任何ID。(编辑:附加屏幕截图,理论似乎得到验证:)
默认情况下,RTK的entityAdapter将查找ID。
基于形实转换程序的代码,似乎有一个uuid。https://redux-toolkit.js.org/api/createEntityAdapter#selectid
因此,您可以将selectId传递给createEntityAdapter,它将针对uuid键。

const valorantAdapter = createEntityAdapter({
  selectId: (valorant) => valorant.uuid,
})

相关问题