[英]React Hooks : fetch data inside useEffect warning
I am using react Hooks useEffect
to fetch data from API in my component我正在使用 react Hooks
useEffect
从组件中的 API 获取数据
props.getUserInfoAction() is an Action from redux dispatching user info
Example例子
useEffect(() => {
props.getUserInfoAction();
}, []);
works great, I can get my data but i found that i have a warning
show up in my console.效果很好,我可以获取我的数据,但我发现我的控制台中出现了
warning
。
React Hook useEffect has a missing dependency: 'props'.
React Hook useEffect 缺少一个依赖项:'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' 会在任何props 改变时改变,所以首选的解决方法是在 useEffect 调用之外解构 'props' 对象,并在 useEffect react-hooks/exhaustive-deps 中引用那些特定的 props
I tried to pass the props
in the array but by doing that i get an infinite loop of API call.我试图传递数组中的
props
,但这样做我得到了 API 调用的无限循环。
useEffect(() => {
props.getUserInfoAction();
}, [props]);
If props.getUserInfoAction()
is an action you should instead of receiving already with a dispatch (from connect
I assume) do this:如果
props.getUserInfoAction()
是一个动作,你应该这样做,而不是已经通过调度接收(来自connect
我假设)这样做:
import {getuserInfoAction} from './actionCreators'
import {useDispatch} from 'react-redux'
const Comp = () =>{
const dispatch = useDispatch()
useEffect(() =>{
dispatch(getUserInfoAction())
},[dispatch])
}
Because even if you do this:因为即使你这样做:
const {action} = props
Functions will always change between render calls.函数将始终在渲染调用之间发生变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.