[英]how to set an useEffect to fetch data from API at first render with eslint-react-hooks?
I need to call two functions to fetch data only on the first render. 我需要调用两个函数来仅在第一个渲染上获取数据。 I'm using react-hooks on this project.
我在这个项目上使用react-hooks。 So the code would look something like this:
所以代码看起来像这样:
const Component = (props) => {
// init
useEffect(() => {
const fetchA = async () => {
await props.fetchA()
};
const fetchB = async () => {
await props.fetchB()
};
fetchA();
fetchB();
}, []);
}
fetchA and fetchB are actions performed by redux to make requests and save data on the reducers. fetchA和fetchB是redux执行的操作,用于在reducers上发出请求和保存数据。
Then I added eslint-react-hooks to the project. 然后我在项目中添加了eslint-react-hooks 。 Now eslint warns me that
现在,eslint警告我
Blockquote React Hook useEffect has a missing dependency: 'props'.
Blockquote 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.
但是,当任何道具发生变化时,“道具”会发生变化,因此首选修复方法是在useEffect调用之外构造“道具”对象,并引用useEffect中的那些特定道具。
Is the only way to do this by applying // eslint-disable-next-line react-hooks/exhaustive-deps
onto the line before the useEffect dependencies? 通过在useEffect依赖项之前将
// eslint-disable-next-line react-hooks/exhaustive-deps
到行上,这是唯一的方法吗?
It's pointing out that if props.fetchA and props.fetchB change, your code is not set up to update with it. 它指出如果props.fetchA和props.fetchB发生变化,你的代码就不会设置为随之更新。 If you're absolutely certain you want to ignore changes to props.fetchA and props.fetchB, then you can add an eslint-disable.
如果您完全确定要忽略对props.fetchA和props.fetchB的更改,则可以添加eslint-disable。
If you want to make your code perform updates when props.fetchA or props.fetchB change, then follow the instructions in the lint warning and do something like this: 如果要在props.fetchA或props.fetchB更改时使代码执行更新,请按照lint警告中的说明执行以下操作:
const { fetchA, fetchB } = props;
useEffect(() => {
// i renamed these so as not to conflict with the outer variables. Feel free to choose different names.
const a = async () => {/* fetchA() */};
const b = async () => {/* fetchB() */};
a();
b();
}, [fetchA, fetchB]);
Depending on what fetchA and fetchB are doing, it's possible you'll need some cleanup logic to undo what was done the first time, but i can't tell you precisely what since i don't know what fetchA and fetchB do. 根据fetchA和fetchB正在做什么,你可能需要一些清理逻辑来撤消第一次做的事情,但我不能准确地告诉你什么,因为我不知道fetchA和fetchB做了什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.