如何在功能组件中只提取一次值?

How to extract a value only once in a functional component?

我试图从 json 文件中仅提取一次值。这意味着我不希望它在组件重新渲染后做同样的工作。我试着用 useEffect() 来做,但由于某种原因,值没有被提取,我得到一个空对象。

import quotes from '../quotes.json'
    function Header () {
        var currentQuote = {}
     
        useEffect(() => {
             currentQuote = quotes.listOfQuotes[Math.floor(Math.random() * quotes.listOfQuotes.length)]
        }, [])
    }

useMemo 会起作用。与 useEffect 相似,只有当依赖数组发生变化时它才会 运行,所以如果你传递一个空的依赖数组,它只会在挂载时 运行。

var currentQuote = useMemo(() => (
  quotes.listOfQuotes[Math.floor(Math.random() * quotes.listOfQuotes.length)]
), []);

如果您希望在您的视图中呈现它,您需要在状态中设置您的值。您已经为 useEffect 提供了一个空数组作为 deps,因此它不会在每次渲染时都被触发。这是 a Stackblitz repro,这是代码:

function Header() {
  const [currentQuote, setCurrentQuote] = React.useState('');
  const [val, setVal] = React.useState(0);
  const quotes = {
    listOfQuotes:['lol', 'test', 'another value', 'super quote']
  };

  React.useEffect(() => {
    console.log('Math.floor(Math.random() * quotes.listOfQuotes.length) = ', Math.floor(Math.random() * quotes.listOfQuotes.length))
    setCurrentQuote(
      quotes.listOfQuotes[
        Math.floor(Math.random() * quotes.listOfQuotes.length)
      ]);
  }, []);

  return (
    <>
      <button onClick={() => setVal(3)}>Edit val</button><br />
      {currentQuote}<br />
      {val}
    </>
  )
}