【问题标题】:React - redux state changes but component is not displaying updated state object propertyReact - redux 状态更改但组件未显示更新的状态对象属性
【发布时间】:2021-05-28 10:42:27
【问题描述】:

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

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

奇怪的是,组件正确显示了成分列表,但没有获取 pagecount 的值(在 state 的 pagination 属性中)。

特别是这两行代码是未定义的。当我将整个对象注销时({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;

【问题讨论】:

  • 成分切片是如何使用的,我没有看到它在任何地方使用过?如果是设置 state.ingredients 那么为什么 state.ingredients 的初始值是一个数组呢?
  • @HMR 我只包含了配置的相关部分。我按照标准文档 (redux-toolkit.js.org/api/configureStore#full-example) 来配置商店。切片减速器通过调用 combineReducer() 导出和组合,然后(即具有所有组合减速器的根减速器)被传递给 configureStore() 将存储返回给我。然后将其传递给包装了我上面的核心组件的提供程序组件。成分是一个数组,因为它是一个分页的对象列表,最初它是空的,因为我必须等待我的 API 响应

标签: reactjs react-redux redux-toolkit


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2018-09-25
    • 2017-09-21
    • 1970-01-01
    相关资源
    最近更新 更多