使用React 16.8.6(在以前的版本16.8.3中很好),当我尝试防止在获取请求上发生无限循环时,出现此错误
./src/components/BusinessesList.js
Line 51: React Hook useEffect has a missing dependency: 'fetchBusinesses'.
Either include it or remove the dependency array react-hooks/exhaustive-deps
Run Code Online (Sandbox Code Playgroud)
我一直找不到停止无限循环的解决方案。我想远离使用useReducer()。我确实在https://github.com/facebook/react/issues/14920找到了这个讨论,在这里可能的解决方案是You can always // eslint-disable-next-line react-hooks/exhaustive-deps if you think you know what you're doing.我不确定自己在做什么,所以我还没有尝试实现它。
我有这个当前设置,React hook useEffect永远/无限循环连续运行,唯一的注释是useCallback()我不熟悉的。
我目前的使用方式useEffect()(类似于,我一开始只想运行一次componentDidMount())
useEffect(() => {
fetchBusinesses();
}, []);
Run Code Online (Sandbox Code Playgroud)
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
}) …Run Code Online (Sandbox Code Playgroud) 根据文件:
componentDidUpdate()更新发生后立即调用.初始渲染不会调用此方法.
我们可以使用新的useEffect()钩子来模拟componentDidUpdate(),但似乎useEffect()是在每次渲染之后运行,甚至是第一次.如何让它不能在初始渲染上运行?
正如您在下面的示例中所看到的,componentDidUpdateFunction在初始渲染期间打印,但componentDidUpdateClass在初始渲染期间未打印.
function ComponentDidUpdateFunction() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log("componentDidUpdateFunction");
});
return (
<div>
<p>componentDidUpdateFunction: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
class ComponentDidUpdateClass extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidUpdate() {
console.log("componentDidUpdateClass");
}
render() {
return (
<div>
<p>componentDidUpdateClass: {this.state.count} times</p>
<button
onClick={() => { …Run Code Online (Sandbox Code Playgroud)