我遇到了状态更改和组件未更新的问题。我所有的研究都指向不正确地改变状态,但我使用 redux-toolkit 来改变改变,所以我不确定问题出在哪里。我正在为我的代码使用打字稿。
我可以确认状态正在分 3 个阶段发生变异。当组件最初呈现时,useEffect 钩子启动,状态通过将 isLoading 设置为 true 来更改。当 API 调用完成时,状态会再次更新,从而导致组件重新渲染。我现在只从州中选择特定项目 - 成分和分页。
奇怪的是,该组件正确显示了成分列表,但没有提取 pagecount(在 state 的分页属性中)的值。
特别是这两行代码被认为是未定义的。当我注销整个对象 ({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;
答案 0 :(得分:0)
我觉得自己像个白痴。所以我上面的所有代码都是正确的。我没有将 API 中的分页值解析为实际对象,因此它是作为字符串而不是实际对象出现的。一旦我修复它就解决了问题。