1

我有一个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>
  );
});
4

1 回答 1

1

defaultMarket为什么,那么如果有tickers更新,您将永远不会重新计算。

如果你真的想要,你可以为该行添加一个 eslint disable 并使用一个空的依赖数组,这样钩子只在组件挂载时运行一次。

const defaultMarket = useMemo(
  () =>
    tickers.find((ticker) => {
      return ticker.market_id === "BTC-USD";
    }),
  // eslint-disable-next-line react-hooks/exhaustive-deps
  []
);
于 2020-05-28T05:05:01.003 回答