Redux : useSelector returns undefined but returns data at 3 rd time

Redux : useSelector returns undefined but returns data at 3 rd time

我正在按预期从 api 获取数据,但这里的问题是我在第三次尝试中获取数据,这导致我的应用程序在没有数据显示时出错。

我正在测试它在控制台上打印,但它是同样的错误。我一刷新页面,错误就涌入控制台

减速器

export const productDetailsReducer = (state = { products: {} }, action) => {
  switch (action.type) {
    case PRODUCT_DETAILS_REQUEST:
      return {
        ...state,
        loading: true,
      };

    case PRODUCT_DETAILS_SUCCESS:
      return {
        loading: false,
        product: action.payload,
      };

    case PRODUCT_DETAILS_FAIL:
      return {
        ...state,
        error: action.payload,
      };

    case CLEAR_ERRORS:
      return {
        ...state,
        error: null,
      };

    default:
      return state;
  }
};

组件

const ProductDetails = () => {
  const dispatch = useDispatch();
  const alert = useAlert();
  const { id } = useParams();
  const { product, loading, error } = useSelector(
    (state) => state.productDetails
  );

  useEffect(() => {
    dispatch(getProductDetails(id));
    if (error) {
      alert.error(error);
      dispatch(clearErrors());
    }
  }, [dispatch, id, alert, error]);

  console.log(product);

动作

export const getProductDetails = (id) => async (dispatch) => {
  try {
    dispatch({ type: PRODUCT_DETAILS_REQUEST });
    const { data } = await axios.get(`/api/v1/product/${id}`);
    dispatch({
      type: PRODUCT_DETAILS_SUCCESS,
      payload: data.product,
    });
  } catch (error) {
    dispatch({
      type: PRODUCT_DETAILS_FAIL,
      payload: error.response.data.message,
    });
  }
};

App.js

function App() {
  return (
    <Router>
      <div className="App">
        <Header />
        <div className="container container-fluid">
          <Routes>
            <Route path="/" element={<Home />} exact />
            <Route path="/product/:id" element={<ProductDetails />} />
          </Routes>
        </div>
        <Footer />
      </div>
    </Router>
  );
}

你没有在初始状态下设置加载我想这就是原因

export const productDetailsReducer = (state = { products: {} }, action) => {

您在设置状态值之前尝试访问加载状态,这就是您收到错误的原因 您应该使用默认值设置初始状态下的加载和错误

const initialState = {products: {}, loading: true, error: null}

然后传给reducer

export const productDetailsReducer = (state = initialState, action) => {

并将产品更改为产品

希望这能解决您的问题。

我检查了你的代码,我认为问题出在你的初始状态

export const productDetailsReducer = (state = { products: {} }, action) => 

尝试将 state={products:{}} 更改为 state={product: {}}