【问题标题】:Using redux with react-hooks without the connect HOC在没有连接 HOC 的情况下使用带有 react-hooks 的 redux
【发布时间】:2020-11-05 05:54:03
【问题描述】:

目前,我正在使用带有钩子的功能组件,但仍在使用 connect HOC 调度我的操作。

我使用 useDispatch 通读了文档,但不确定如何将其合并到我的代码中。从示例中,它们在组件内传递动作类型和有效负载。我是否必须将 myOfferActions 函数移回组件才能使用 Dispatch?

MyOffers 组件

import React, { useEffect } from "react";
import { connect, useSelector } from "react-redux";
import "./MyOffers.scss";
import MyOfferCard from "../../components/MyOfferCard/MyOfferCard";
import { fetchMyOffers } from "../../store/actions/myOffersActions";

const MyOffers = (props) => {
  const myOffers = useSelector((state) => state.myOffers.myOffers);

  useEffect(() => {
    props.fetchMyOffers();
  }, []);

  return (
    <div className="my-offers-main">
      <h1>My offers</h1>
      {myOffers && (
        <div className="my-offer-container">
          {myOffers.map((offer) => (
            <MyOfferCard key={offer.id} offer={offer} />
          ))}
        </div>
      )}  
    </div>
  );
};

export default connect(null, { fetchMyOffers })(MyOffers);

offerActions

export const fetchMyOffers = () => async (dispatch) => {
  const userId = localStorage.getItem("userId");
  try {
    const result = await axiosWithAuth().get(`/offers/${userId}`);
    let updatedData = result.data.map((offer) => {
      //doing some stuff
      };
    });
    dispatch(updateAction(FETCH_MY_OFFERS, updatedData));
  } catch (error) {
    console.log(error);
  }
};

offerReducer

import * as types from "../actions/myOffersActions";

const initialState = {
  offerForm: {},
  myOffers: [],
};

function myOffersReducer(state = initialState, action) {
  switch (action.type) {
    case types.FETCH_MY_OFFERS:
      return {
        ...state,
        myOffers: action.payload,
      };
    default:
      return state;
  }
}

export default myOffersReducer;

【问题讨论】:

    标签: javascript reactjs redux react-hooks


    【解决方案1】:

    我认为你在使用 redux 钩子时不需要connect

    你只需要像这样调用 useDispatch : const dispatch = useDispatch();

    并通过提供标识动作的对象来使用该功能:

    dispatch({ type: 'SOME_ACTION', payload: 'my payload'});

    它也应该与 redux-thunk 一起使用(我想这就是你正在使用的):dispatch(fetchMyOffers())

    【讨论】:

    • 有没有办法实现它,您不必用dispatch 包装所有内容?使用connect,您只需致电fetchMyOffers()。也许有一个钩子可以像这样调度动作:const { dispatchFetchMyOffers } = useAction({ fetchMyOffers } );
    • 我不知道这样的钩子,至少在 react-redux 包中。
    • 你不能使用没有功能组件的钩子
    猜你喜欢
    • 2017-04-13
    • 2020-01-06
    • 2018-09-14
    • 2020-10-09
    • 2019-02-25
    • 2016-09-27
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多