我有一个MarketOverview
组件可以呈现一堆加密货币交易对市场。在初始化时,我希望它默认呈现BTC/USD
市场,我正在通过useEffect()
. 问题是defaultMarket
每次渲染都会调用。此外,defaultMarket
取决于tickers
道具,所以如果我将它包装在 中useMemo()
,那么 eslint react-hooks 插件会自动填充tickers
为依赖项。
没有useMemo()
:
const defaultMarket = tickers.find((ticker) => {
return ticker.market_id === "BTC-USD";
});
与useMemo()
:
const defaultMarket = useMemo(
() =>
tickers.find((ticker) => {
return ticker.market_id === "BTC-USD";
}),
[tickers]
);
整个组件:
export const MarketOverview = memo(({ tickers }: TProps) => {
// Set default market on initialisation to BTC/USD
const defaultMarket = tickers.find((ticker) => {
return ticker.market_id === "BTC-USD";
});
const [selectedMarket, setSelectedMarket] = useState<ITicker | undefined>(
undefined
);
useEffect(() => {
setSelectedMarket(defaultMarket);
}, [defaultMarket]);
// Select market
const selectMarket = (market: ITicker) => {
history.push(`${PUBLIC_URL}/markets/${market.market_id}`);
setSelectedMarket(market);
};
return (
<div className="market-overview-container">
<MarketSelector
tickers={tickers}
selectMarket={selectMarket}
selectedMarket={selectedMarket}
/>
{selectedMarket && <MarketStats selectedMarket={selectedMarket} />}
</div>
);
});