action.js
import actionTypes from "./actionTypes";
import axios from "axios";
export const getSeries = () => {
return {
type: actionTypes.SERIES_REQUEST,
payload: axios.get("/api/series.json")
};
};
import React,{useEffect} from 'react';
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import { getSeries } from "../../../actions/series";
export function Header() {
const series = useSelector(state => state, shallowEqual);
const dispath = useDispatch();
useEffect(() => {
//第一次请求
dispath(getSeries());
}, []);
return (
<div className="header"></div>
);
}
export function Home() {
const series = useSelector(state => state, shallowEqual);
const dispath = useDispatch();
useEffect(() => {
//第二次请求
dispath(getSeries());
}, []);
return (
<div className="home"></div>
);
}
遇到的问题 现在会发送两次相同的请求,浪费资源。
请问如何只发送一次请求,两个组件会使用同一份数据
可以看下:createGlobalState
提供一个对hooks友好,有十分轻便的方案,共享全局数据
HOC更适合Class组件