useSelector 即使在发送后也没有更新

useSelector not updating even after dispatch

我正在尝试使用从 reducer 获取的 axios 结果显示产品,但是 useSelector 值不会改变,即使在发送后仍然是空的。我已经检查了 axios 结果并且响应有正确的数据。跟redux文档上的这一行有关系吗?

With useSelector(), returning a new object every time will always force a re-render by default.

减速器

import axios from "axios";

export const products = (state = [], action) => {
  switch (action.type) {
    case "FETCH_PRODUCTS": {
      const uri = "/products";

      axios.get(uri).then(function (response) {
        if (response.status == 200) {
          console.log(response.data.products); // ===> correct new value
          return { state: response.data.products };
        }
      });
    }

App.js

import React, { useEffect } from "react";
import { shallowEqual, useSelector, useDispatch } from "react-redux";
import "../css/App.css";

import { Products, Navbar, Cart } from "../components";

function App() {
  const dispatch = useDispatch();

  const products = useSelector((state) => state.products, shallowEqual);
  const cart = useSelector((state) => state.cart, shallowEqual);

  useEffect(() => {
    dispatch({
      type: "FETCH_PRODUCTS",
    });

    console.log(products); // ===> still empty array
  }, []);

  return (
    <div className="App">
      <Navbar />
      <Cart cart={cart} />
      <Products products={products} />
    </div>
  );
}

export default App;

您应该首先创建您的动作

import axios from 'axios';

export const fetchProducts = () => async (dispatch) => {
    try {
        const { data } = await axios.get('...');

        dispatch({ type: "FETCH_PRODUCTS", payload: data.result });
    } catch (error) {
        console.log(error);
    }
};

然后,一起使用dispatchaction

import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { fetchProducts } from './actions';

const getSelectors = state => ({ cart: state.cart, products: state.products });
const App = () => {
    const dispatch = useDispatch();
    const {cart, products} = useSelector(getSelectors);

    useEffect(() => {
        dispatch(fetchProducts());
    }, []);

    return (
        <div className="App">
          <Navbar />
          <Cart cart={cart} />
          <Products products={products} />
        </div>
    );
};