React Redux useSelector在传递数据时遇到问题



我正在使用带有Redux的React。Redux devtool控制台显示数据存在于状态(Redux devtools控制台(,但网页显示一个错误,表示对象未定义(error(。

这是我的屏幕代码:

import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { listProductDetails } from "../redux/actions/productActions";
const ProductScreen = ({ match }) => {
const dispatch = useDispatch();
const productDetails = useSelector((state) => state.productDetails);
const { loading, error, product } = productDetails;
useEffect(() => {
dispatch(listProductDetails(match.params.id));
}, [dispatch, match]);
return <div>{product.name}</div>;
};
export default ProductScreen;

这是我的redux reducer的代码:

import {
PRODUCT_DETAILS_FAIL,
PRODUCT_DETAILS_REQUEST,
PRODUCT_DETAILS_SUCCESS,
} from "../constants";
export const productDetailsReducer = (state = { product: {} }, action) => {
switch (action.type) {
case PRODUCT_DETAILS_REQUEST:
return { loading: true };
case PRODUCT_DETAILS_SUCCESS:
return { loading: false, product: action.payload };
case PRODUCT_DETAILS_FAIL:
return { loading: false, error: action.payload };
default:
return state;
}
};

这是我行动的代码:

import axios from "axios";
import {
PRODUCT_DETAILS_FAIL,
PRODUCT_DETAILS_REQUEST,
PRODUCT_DETAILS_SUCCESS,
} from "../constants";
export const listProductDetails = (id) => async (dispatch) => {
try {
dispatch({
type: PRODUCT_DETAILS_REQUEST,
});
const { data } = await axios.get(`/api/products/${id}`);
dispatch({
type: PRODUCT_DETAILS_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: PRODUCT_DETAILS_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};

我真的找不到这里的问题,任何帮助都将不胜感激!

我认为问题是,当您调度PRODUCT_DETAILS_REQUEST操作时,reducer将用{ loading: true }覆盖状态值,因此product将是undefined,而不是空对象{}

因此,您应该在reducer中返回具有先前状态的合并对象。例如return { ...state, loading: true };

希望它能帮助你。

export const productDetailsReducer = (state = { product: {} }, action) => {
switch (action.type) {
case PRODUCT_DETAILS_REQUEST:
return { ...state, loading: true };
case PRODUCT_DETAILS_SUCCESS:
return { ...state, loading: false, product: action.payload };
case PRODUCT_DETAILS_FAIL:
return { ...state, loading: false, error: action.payload };
default:
return state;
}
};

相关内容

  • 没有找到相关文章

最新更新