将useDispatch和useSelector与异步操作React-Redux钩子一起使用时,没有得到任何结果

时间:2019-07-28 01:57:03

标签: reactjs redux

最近我一直在学习如何使用Redux,并决定将我的一个类重构为带有钩子的功能组件。但是,当我分派动作时,我没有得到任何结果。

产品组件:

const Products = () =>   {

  const products = useSelector(state => state.products)
  const dispatch = useDispatch();

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


    return (
      <Container>
        <Top>
          <StyledNavLink to="/products/add">Add Product </StyledNavLink>
        </Top>
        <ProductList products={products} />
      </Container>
    );
  }

export default Products;

操作:

export const fetchProducts = () => async (dispatch) => {

  try {
    const response = await api.get("/products");

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

}

减速器:

const productReducer = (state = [], action) => {
  switch (action.type) {
    case "ADD_PRODUCT":
      return state

    case "FETCH_PRODUCTS":
      return action.payload

    default:
      return state;
  }
};

Root Reducer:

import productReducer from "./productReducer";
import { combineReducers } from "redux";

const rootReducer = combineReducers({
  products: productReducer
});

索引:

const store = createStore(rootReducer, applyMiddleware(thunk));

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector("#root")
);

当我使用类组件时,代码将返回值。

0 个答案:

没有答案