【问题标题】:How to extract a value only once in a functional component?如何在功能组件中只提取一次值?
【发布时间】:2021-05-19 21:33:36
【问题描述】:

我只尝试从 json 文件中提取一个值一次。这意味着一旦组件重新渲染,我不希望它做同样的工作。我尝试使用 useEffect() 执行此操作,但由于某种原因该值没有被提取并且我得到一个空对象。

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

【问题讨论】:

    标签: reactjs use-effect react-functional-component


    【解决方案1】:

    useMemo 可以。和useEffect类似,它只会在依赖数组改变时运行,所以如果你传递一个空的依赖数组,它只会在挂载时运行。

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

    【讨论】:

    • 只是好奇useEffect 中的setState 可以工作,为什么原始代码不能工作。顺便说一句,这是我没想到的好方法。
    • 可以,但是在效果钩子运行之前组件会被渲染一小段时间,所以用户屏幕上可能会有轻微的闪烁或其他东西。 useLayoutEffect 会在屏幕被绘制之前通过更快地运行来修复它。但我认为useMemo 更容易。
    • 我收到“'useMemo' is not defined no-undef”错误。有什么想法吗?
    • @aratata 你需要从 React 导入。
    • 这确实有道理:D 谢谢!
    【解决方案2】:

    如果您希望在视图中呈现值,则需要将值设置为状态。您已经为 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}
        </>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2010-09-26
      相关资源
      最近更新 更多