目前,我使用带有钩子的功能组件,但仍使用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;
我认为在使用redux挂钩时不需要connect
。
您只需要调用useDispatch,如下所示:const dispatch = useDispatch();
并通过提供识别动作的对象来使用该功能:
dispatch({ type: 'SOME_ACTION', payload: 'my payload'});
它也应该与redux-thunk
一起工作(我想这就是你正在使用的(:dispatch(fetchMyOffers())