简体   繁体   English

可以使用组件内的 useEffect 更新 useMemo 记忆值吗?

[英]Can a useMemo memoized value be updated with useEffect from within the component?

I'm trying to render data that must be passed through useMemo .我正在尝试呈现必须通过useMemo传递的数据。 I get the data from an api call so I call useEffect .我从 api 调用中获取数据,所以我调用useEffect The initial render works returning an empty array but once I call the api, data is not updated.初始渲染工作返回一个空数组,但是一旦我调用 api,数据就不会更新。

import React from 'react'
import {fetchAccounts} from '../utils/api'

export default function Accounts() {
    const [accounts, setAccounts] = React.useState([])

React.useEffect(() => {
    setLoading(true)
    fetchAccounts().then((data) => {
        setAccounts(data)
    })
}, [])
const data = React.useMemo(() => accounts, [])

return <p>{JSON.stringify(data)}</p>}

So can this work within a single component?那么这可以在单个组件中工作吗? Or must a custom hook be created?还是必须创建自定义挂钩?

The data is not updated because you missing a value in the dependency array.数据未更新,因为您缺少依赖数组中的值。

const data = React.useMemo(() => accounts, [accounts]);

Therefore in this case, it does not make sense to use useMemo since the state is stable anyways, till you change the state.因此在这种情况下,使用useMemo是没有意义的,因为 state 无论如何都是稳定的,直到您更改 state。

You use useMemo and useEffect with the dependency of [] means it run during mounting means it run for once's您使用useMemouseEffect与 [] 的依赖关系意味着它在安装期间运行意味着它运行一次

Let see How useMemo() works让我们看看 useMemo() 是如何工作的

useMemo(()=>{

})

It will run every time if any change occur如果发生任何变化,它将每次运行

useMemo(()=>{

},[])

It will run once's during component mounting它将在组件安装期间运行一次

  useMemo(()=>{

   },[arr])

It will run every time if any changes occur in arr如果arr发生任何更改,它将每次运行

If you have confusion what is the difference between useEffect() and useMemo()如果您感到困惑,那么 useEffect() 和 useMemo() 之间有什么区别

useMemo() is only run when it find any changes it compare latest changes with the previous changes if it find any changes then useMemo run useMemo() 仅在发现任何更改时运行,它将最新更改与以前的更改进行比较,如果发现任何更改,然后useMemo运行

useEffect() is run for every changes if the updated state is same as previous state useEffect don't care it start re render the component.如果更新的 state 与之前的 state useEffect don't care it start re render the component,则每次更改都会运行 useEffect()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM