gpt4 book ai didi

reactjs - React hooks fetch 不会停止获取

转载 作者:行者123 更新时间:2023-12-03 15:21:38 25 4
gpt4 key购买 nike

我正在尝试使用 React 钩子(Hook)来重建一些作为功能组件的类组件来进行获取。

我可以获取数据,这很好,但它每隔几毫秒调用一次我的 API,我只希望它获取数据并停止,就像它在具有 componentDidMount 的类组件中一样。

我想我可以明白它为什么会这样做(函数内部的 fetchData() 意味着它会继续调用自己)但我不确定如何修复它。

我尝试添加一个 setInterval,更改顺序,并将 fetchData() 移到函数之外(组件不会呈现,因为它当时是未定义的)。

const MyFunction = () => {

const [apiResponse,setApiResponse] = useState({})

async function fetchData() {

const res = await fetch(`http://localhost:9000/example`,{
method: 'POST',
mode: 'cors',
body: JSON.stringify({date: '20190707'}),
headers: {'content-type': 'application/json',
credentials: 'include'
}
})
res
.json()
.then(res => setApiResponse(res))
}

useEffect(() => {

fetchData();

});


var queryResult = apiResponse['units']


return (
<React.Fragment>
<CardHeader color={"info"} stats icon>
<CardIcon color={"info"}>
<Icon>{"trending_up"}</Icon>
</CardIcon>
<p className={''}>Drop In</p>
<h3 className={''}>
{queryResult} <small>Units</small>
</h3>
</CardHeader>
<CardFooter ></CardFooter>
</React.Fragment>
);

}

最佳答案

尝试在 useEffect 末尾添加一个空数组:

useEffect(() => {

fetchData();

}, []);

react 文档: https://reactjs.org/docs/hooks-effect.html

Note

If you use this optimization, make sure the array includes all values from the component scope (such as props and state) that change over time and that are used by the effect. Otherwise, your code will reference stale values from previous renders. Learn more about how to deal with functions and what to do when the array changes too often.

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

If you pass an empty array ([]), the props and state inside the effect will always have their initial values. While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often. Also, don’t forget that React defers running useEffect until after the browser has painted, so doing extra work is less of a problem.

We recommend using the exhaustive-deps rule as part of our eslint-plugin-react-hooks package. It warns when dependencies are specified incorrectly and suggests a fix.

关于reactjs - React hooks fetch 不会停止获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56926282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com