在我的 react-typescript 应用程序中,我正在尝试使用一个上下文提供程序来封装属性和方法并将它们公开给消费者:
const StockPriceConsumer: React.FC = () => {
const stockPrice = useContext(myContext);
let val = stockPrice.val;
useEffect(() => {
stockPrice.fetch();
}, [val]);
return <h1>{val}</h1>;
};
问题是以下警告:
React Hook useEffect 缺少依赖项:'stockPrice'。包括它或删除依赖数组。eslint(react-hooks/exhaustive-deps)
stockPrice
对我来说,将(基本上是提供者的 API)包含到 useEffect 的依赖项中没有任何意义。只有包含股票价格的实际价值以防止无限调用 useEffect 函数才有意义。
问题:我尝试使用的方法有什么问题,或者我可以忽略这个警告吗?
提供者:
interface StockPrice {
val: number;
fetch: () => void;
}
const initialStockPrice = {val: NaN, fetch: () => {}};
type Action = {
type: string;
payload: any;
};
const stockPriceReducer = (state: StockPrice, action: Action): StockPrice => {
if (action.type === 'fetch') {
return {...state, val: action.payload};
}
return {...state};
};
const myContext = React.createContext<StockPrice>(initialStockPrice);
const StockPriceProvider: React.FC = ({children}) => {
const [state, dispatch] = React.useReducer(stockPriceReducer, initialStockPrice);
const contextVal = {
...state,
fetch: (): void => {
setTimeout(() => {
dispatch({type: 'fetch', payload: 200});
}, 200);
},
};
return <myContext.Provider value={contextVal}>{children}</myContext.Provider>;
};