我遇到了状态改变和组件不更新的问题。我所有的研究都指向不正确的突变状态,但我正在使用redux-toolkit突变变化,所以我不确定问题在哪里。我使用typescript为我的代码。
我可以确认状态在三个阶段发生突变。当组件初始渲染时,useEffect钩子启动,通过设置isLoading改变状态。为true。当API调用完成时,状态将再次更新,从而导致组件重新呈现。我现在只从状态中选择特定的项目——成分和分页。
奇怪的是组件正确地显示了成分列表,但是pagecount的值(在分页属性from 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;
我觉得自己像个白痴。所以上面所有的代码都是正确的。我没有将API中的分页值解析为实际对象,所以它是作为字符串而不是实际对象传入的。我一修好它,问题就解决了。