React - redux 状态更改但组件未显示更新的状态对象 属性

React - redux state changes but component is not displaying updated state object property

我 运行 遇到状态更改和组件未更新的问题。我所有的研究都指向不正确地改变状态,但我正在使用 redux-toolkit 来改变变化,所以我不确定问题出在哪里。我正在为我的代码使用打字稿。

我可以确认状态分 3 个阶段发生变化。当组件最初呈现时,useEffect 挂钩启动,通过将 isLoading 设置为 true 来更改状态。 API 调用完成后,状态会再次更新,导致组件重新呈现。我现在只从状态中选择特定项目 - 成分和分页。

奇怪的是,该组件正确显示成分列表,但 pagecount 的值(在分页 属性 从状态)没有被拾取。

特别是这两行代码被认为是未定义的。当我注销整个对象时 ({console.log(pagination)}) 我确实看到在重新呈现后记录了正确的值。为什么分页的 属性 在所有重新渲染之间都未定义?它甚至在页面加载开始时(在 useEffect 钩子之前)是未定义的,即使它在初始状态下明确设置。

<Pagination count={pagination.totalPages}

<p>page count: {pagination.totalPages}</p>

以上

const ingredients: Ingredients[] = [];
const pagination: XPaginationDto = {
  currentPage: 1,
  pageSize: 5,
  totalCount: 0,
  totalPages: 0,
  nextPageLink: "",
  previousPageLink: "",
};

const initialState = {
  ingredients,
  isLoading: false,
  errorMessage: "",
  pagination,
};

export const getIngredientsAction = createAsyncThunk(
  "ingredients/getIngredients",
  async (options: RequestOptionDto, { dispatch }) => {
    try {
      const response = await ingredientsApi.getIngredients(options);
      return response;
    } catch (e) {
      dispatch(getIngredientsFailure(e));
    }
  }
);

const ingredientSlice = createSlice({
  name: "ingredients",
  initialState,
  reducers: {
    getIngredientsSuccess: (
      state,
      action: PayloadAction<PaginatedIngredients>
    ) => {
      state.ingredients = action.payload.ingredients;
      state.pagination = action.payload.xPaginationDto;
    },
    getIngredientsFailure: (state, action: PayloadAction<string>) => {
      state.isLoading = false;
      state.errorMessage = action.payload;
    },
  },
  extraReducers: {
    // @ts-ignore
    [getIngredientsAction.pending]: (state, action) => {
      state.isLoading = true;
    },
    // @ts-ignore
    [getIngredientsAction.fulfilled]: (state, action: any) => {
      const paginatedIngredients = action.payload as PaginatedIngredients;
      state.isLoading = false;
      state.ingredients = paginatedIngredients.ingredients;
      state.pagination = paginatedIngredients.xPaginationDto;
    },
    // @ts-ignore
    [getIngredientsAction.rejected]: (state, action) => {
      state.isLoading = false;
    },
  },
});

我的状态设置如上。我的组件设置也相当简单:

const IngredientsList: React.FC = () => {
  const dispatch = useAppDispatch();
  const { ingredients, pagination, renderCount } = useSelector(
    (state: RootState) => state.ingredients
  );
  const [page, setPage] = React.useState(1);

  const handlePagination =//some function to handle pagination

  useEffect(() => {
    console.log("test");
    dispatch(
      getIngredientsAction({
        pageNumber: 1,
        pageSize: 5,
        sorts: "lastupdated",
      } as RequestOptionDto)
    );
  }, [dispatch, page]);

  return (
    <>
        <p>pagination value: {console.log(pagination)}</p>
        <p>page count: {pagination.totalPages}</p>
        {ingredients.map((x, index) => {
          return (
            <some component>
          );
        })}
      </Grid>

      <div>
        <Typography>Page: {page}</Typography>
        <Pagination
          count={pagination.totalPages}
          page={page}
          variant="outlined"
          onChange={handlePagination}
          color="secondary"
        />
      </div>
    </>
  );
};

export default IngredientsList;

我觉得自己像个白痴。所以我上面的所有代码都是正确的。我没有将 API 中的分页值解析为实际对象,因此它是作为字符串而不是实际对象通过的。我一修复它就解决了问题。