我正在尝试更新状态并在组件中呈现更新的值,但无法实现。
<-这是我的动作->
export const fetchProducts = () => async (dispatch) => {
const res = await fakeApi.get("/products");
console.log(res.data);
dispatch({
type: FETCH_PRODUCTS,
payload: res.data,
});
};
<-这里是减速器->
const initialState = {
products: [],
};
export default (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
case FETCH_PRODUCTS:
return { ...state, products: payload };
default:
return state;
}
};
<-这里是组件->
const Products = ({ products, fetchProducts }) => {
const [productsList,setProductsList]=useState([])
useEffect(() => {
fetchProducts();
console.log(products);
setProductsList({productsList:products})
}, []);
return <ProductList products={productsList} />;
};
const mapStateToProps = (state) => ({
products: state.products,
});
export default connect(mapStateToProps, { fetchProducts })(Products);
<-这是我第一次使用redux。我不知道我要去哪里错。我得到的一切在状态中都是不确定的。 ->
答案 0 :(得分:0)
您正在对基于功能的组件使用react钩子,在这种特定情况下,使用useSelector()钩子代替mapStateToProps可能会更容易从redux存储中获取数据,因为我看不到您的名字您在根减速器中的减速器,我假设它名为productReducer,请在您的组件中尝试以下操作:
import {useSelector} from 'react-redux'
...
let products = useSelector(state=>state.productReducer.Products)