useEffect - 无法对未安装的组件执行 React 状态更新 [英] useEffect - Can't perform a React state update on an unmounted component

查看:39
本文介绍了useEffect - 无法对未安装的组件执行 React 状态更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个网站,其中列出了几个空缺职位.

我想在组件安装后GET所有工作职位.因此,我使用了useEffect.我在 useEffect 中设置状态,我认为这是导致错误的原因:

<块引用>

警告:无法对卸载的组件执行 React 状态更新.

我想知道如何解决此警告.我不明白为什么我不能在 useEffect

中设置状态

我的组件

function MyComponent({changeType}) {const [user, setUser] = React.useState([]);const [positions, setPositions] = React.useState([]);异步函数 getAllPositions(){let response = await axios("http://www.localhost:3000/api/v1/positions");设置位置(响应.数据)}useEffect(()=>{让 jwt = window.localStorage.getItem('jwt')让结果 = jwtDecode(jwt)设置用户(结果)changeType() # 这是一个将 props 传递给MyComponent"的父级的函数getAllPositions()}, [],)返回(<div>某物

)}

解决方案

在异步调用后更新状态之前,您应该检查组件是否仍然挂载

useEffect(()=>{让卸载 = false异步函数 getAllPositions(){let response = await axios("http://www.localhost:3000/api/v1/positions");如果(!卸载)设置位置(响应.数据)}让 jwt = window.localStorage.getItem('jwt')让结果 = jwtDecode(jwt)设置用户(结果)getAllPositions()返回 () =>{未安装 = 真}}, [])

I am creating a website that lists several open job positions.

I want to GET all the job positions once the component mounts. Therefore, I used useEffect. I am setting the state inside useEffect, which I think is causing the error:

Warning: Can't perform a React state update on an unmounted component.

I would like to know how I can fix this warning. I am not understanding why I cannot set the state inside useEffect

My component

function MyComponent({changeType}) {
    const [user, setUser] = React.useState([]);
    const [positions, setPositions] = React.useState([]);

    async function getAllPositions(){
        let response = await axios("http://www.localhost:3000/api/v1/positions");
        setPositions(response.data)
    }


    useEffect( ()=> {
        let jwt = window.localStorage.getItem('jwt')
        let result = jwtDecode(jwt)
        setUser(result)
        changeType() # It is a function passing props to the parent of "MyComponent"
        getAllPositions()
        }, [],
    )
    return(
        <div>
         Something
        </div>
    )
}

解决方案

You should check if component is still mounted before update state after an async call

useEffect( ()=> {
       let unmounted = false
       async function getAllPositions(){
            let response = await  axios("http://www.localhost:3000/api/v1/positions");
            if(!unmounted)
                setPositions(response.data)
        }
        let jwt = window.localStorage.getItem('jwt')
        let result = jwtDecode(jwt)
        setUser(result)
        getAllPositions()
        return () => {
             unmounted = true
        }
}, [])

这篇关于useEffect - 无法对未安装的组件执行 React 状态更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆