【发布时间】:2020-09-10 03:13:49
【问题描述】:
在我的 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>;
};
【问题讨论】:
-
经验法则:你想忽略的感觉
react-hooks/exhaustive-deps== 你的副作用正在对抗 Thinking in React 第 4 步:确定你的州应该住在哪里
标签: reactjs react-context use-effect use-reducer