我基本上是试图保存喜欢/不喜欢的状态的产品列表,我试图从API获取使用axios,但我得到下面的错误.
在状态中检测到不可序列化的值,路径为:'产品。价值:{"_x ":0"_y ",_z":空,"_A":空}
为了保存状态,我尝试使用Redux工具包。下面我有productSlice
组件和ProductListScreen
组件的代码。
productSlice.js
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const productsSlice = createSlice({
name: "products",
initialState: { items: [], likes: [] },
reducers: {
fetchProducts: async (state) => {
const response = await axios.get("https://dummyjson.com/products");
state.items = response.data;
state.likes = new Array(state.items.length).fill(false);
},
toggleLike: (state, action) => {
state.likes[action.payload.index] = action.payload.isLiked;
},
},
});
export const { fetchProducts, toggleLike } = productsSlice.actions;
export default productsSlice.reducer;
productListScreen.js
import { useEffect, useState } from "react";
import { FlatList, Text, View } from "react-native";
import { useDispatch, useSelector } from "react-redux";
import { fetchProducts, toggleLike } from "./productsSlice";
const ProductListScreen = () => {
const products = useSelector((state) => state.products.items);
const likes = useSelector((state) => state.products.likes);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchProducts());
}, []);
const handleLike = (index, isLiked) => {
dispatch(toggleLike({ index, isLiked }));
};
const renderItem = ({ item, index }) => (
<View>
<Text>{item.title}</Text>
<LikeDislikeButton
productId={item.id}
liked={likes[index]}
onPress={() => handleLike(index, !likes[index])}
/>
</View>
);
return (
<View>
<FlatList
data={products}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
</View>
);
};
export default ProductListScreen;
2条答案
按热度按时间deikduxw1#
Reducer函数应该是纯***同步***函数。您已经声明了
fetchProducts
Reducer函数async
,它 * 隐式 * 返回Promise对象。这是存储到state.products
中的不可序列化对象。您应该创建和使用异步操作(即Thunk)来进行异步API调用。将
fetchProducts
重构为异步操作。使用productSlice
的extraReducers
来处理从fetchProducts
thunk返回的已履行承诺。gdrx4gfi2#
response.data
是包含产品列表的对象。