React Hooks:在 useEffect 警告中获取数据 [英] React Hooks : fetch data inside useEffect warning

查看:72
本文介绍了React Hooks:在 useEffect 警告中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react Hooks useEffect 从我的组件中的 API 获取数据

I am using react Hooks useEffect to fetch data from API in my component

props.getUserInfoAction() is an Action from redux dispatching user info 

示例

useEffect(() => {
        props.getUserInfoAction();
      }, []);

效果很好,我可以获取我的数据,但我发现我的控制台中显示了warning.

works great, I can get my data but i found that i have a warning show up in my console.

React Hook useEffect 缺少依赖项:'props'.要么包括它或删除依赖项数组.但是,道具"会在any 道具更改,因此首选的解决方法是在 useEffect 调用之外解构道具"对象并引用这些特定道具内部 useEffect react-hooks/exhaustive-deps

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when any prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps

我试图在数组中传递 props 但这样做我得到了 API 调用的无限循环.

I tried to pass the props in the array but by doing that i get an infinite loop of API call.

useEffect(() => {
            props.getUserInfoAction();
          }, [props]); 

推荐答案

如果 props.getUserInfoAction() 是一个你应该的动作,而不是已经通过调度接收(来自 connect代码>我假设)这样做:

If props.getUserInfoAction() is an action you should instead of receiving already with a dispatch (from connect I assume) do this:

import {getuserInfoAction} from './actionCreators'
import {useDispatch} from 'react-redux'

const Comp = () =>{
    const dispatch = useDispatch()

    useEffect(() =>{
        dispatch(getUserInfoAction())
    },[dispatch])
}

因为即使你这样做:

const {action} = props

函数总是会在渲染调用之间发生变化.

Functions will always change between render calls.

这篇关于React Hooks:在 useEffect 警告中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆