简体   繁体   English

将 axios 响应保存到 state 反应钩子

[英]Save axios response to state react hooks

I am trying to save the response I get from Axios to state using hooks.我正在尝试使用钩子保存从 Axios 到 state 的响应。 However, whenever I attempt to use the hook, the component continues to re-render an unlimited number of times.但是,每当我尝试使用钩子时,组件都会继续重新渲染无限次。

const [orders, setOrders] = useState([]);

const getUserOrders = async () => {
        await API.getOrders(window.sessionStorage.id)
            .then(res => setOrders(res.data.ordersArr))
            .catch(err => console.log(err));
}
useEffect(() => {
        if (logged_in) {
            getUserOrders();
        } else {
            window.location.href = "/login";
        }
}, [orders])

If I console log res.data.ordersArr instead of using the setOrders hook, I am able to see the expected data.如果我控制台日志 res.data.ordersArr 而不是使用 setOrders 挂钩,我可以看到预期的数据。 When I use the hook, it keeps re-rendering.当我使用钩子时,它会不断重新渲染。

Your useEffect hook will re-run each time the orders state changes, when your useEffect hook runs you fetch data from the API and then set the orders .每次orders state 更改时,您的useEffect挂钩都会重新运行,当您的useEffect挂钩运行时,您会从 API 获取数据,然后设置orders This in turn then triggers a render with a new value for orders thus invalidating the useEffect call and causing it to fire again which ultimately leads to the infinite loop.这反过来又会触发具有新orders值的渲染,从而使useEffect调用无效并导致它再次触发,最终导致无限循环。

You simply want to force the useEffect to run once by passing an empty dependency list useEffect(..., [])您只是想通过传递一个空的依赖项列表来强制useEffect运行一次useEffect(..., [])

There are couple of things you need to refactor您需要重构几件事

  1. your React Hook useEffect has dependency orders which will re render unlimited times你的 React Hook useEffect 有依赖orders ,它将无限次重新渲染
  2. .then after await dont make any sense, either get rid of async / await or include the promise callback .then在 await 之后没有任何意义,要么摆脱 async / await 要么包括 promise 回调

    const getUserOrders = () => {
            API.getOrders(window.sessionStorage.id)
                .then(res => setOrders(res.data.ordersArr))
                .catch(err => console.log(err));
    }
    useEffect(() => {
            if (logged_in) {
                getUserOrders();
            } else {
                window.location.href = "/login";
            }
    }, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM