我的react应用程序没有那么大的项目,我决定不使用Redux,所以我在useFetch自定义钩子中使用useReducer钩子进行状态管理:
import ...
export const useFetch = (programType) => {
const [state, dispatch] = useReducer(reducer, Initial_State);
const { entries, isFetching, errorMessage } = state;
useEffect(() => {
dispatch(fetchBegin());
const fetchData = async () => {
try {
await new Promise((resolve, reject) => setTimeout(resolve, 1480)); //testing withSpinner HOC for loading screen.
const res = await fetch(
'https://5f706444bdb178001633bf46.mockapi.io/data'
);
const dataArray = await res.json();
dispatch(fetchSuccess(dataArray[0].entries, programType));
} catch (errorMessage) {
dispatch(fetchFail(errorMessage));
}
};
fetchData();
}, [programType]);
return { entries, isFetching, errorMessage };
};
我在我的moviePage组件中调用了useFetch钩子,但是我的组件渲染了很多次,控制台日志记录在组件挂载时渲染4次,然后再次记录2次。
import ...
const MoviePage = ({ match }) => {
const data = useFetch('movie');
const { entries } = data;
console.log('render');
return (
<>
<RouteTitle title={match.path} />
{entries.slice(0, 21).map((e) => (
<div key={e.title}>{e.title}</div>
))}
</>
);
};
useEffect挂钩是否是这种不良模式,应该将redux与useDispatch和useSelector挂钩一起使用?