简体   繁体   English

无法在 ReactJS 中设置 useState 钩子的值

[英]Can't able to set the value for useState hook in ReactJS

I used axios to access the 'http://localhost:8000/api/lists/', after accessing it, if I use console.log() , then the values are printing in console, but while setting the state it shows an empty array.. how to set the values of res.data to setArrData().我使用 axios 访问“http://localhost:8000/api/lists/”,在访问它之后,如果我使用 console.log() ,那么这些值将在控制台中打印,但是在设置状态时它会显示一个空数组.. 如何将 res.data 的值设置为 setArrData()。 can anyone help to solve it ?...谁能帮忙解决一下?...

const [arrData, setArrData] = React.useState([])
useEffect(()=>
        getData()
},[])

const getData=()=>{
    let inp=field.inp

    axios.post('http://localhost:8000/api/lists/',{
            'input':inp
        },
        {
            headers:{'Content-Type': 'application/json'},
        }
    ).then(res=>{
        if(res.status===200){
            setArrData(res.data)
            console.log(arrData)
            console.log(res.data)
        }
    }).catch(err=>console.log(err))
}

Because setState in asynchronous , so you can't see new state after setState .因为setStateasynchronous ,所以在setState之后你看不到新的状态。 If you want to see the change of the arrData , you can use useEffect :如果你想看到arrData的变化,你可以使用useEffect

useEffect(() => {
  console.log(arrData);
}, [arrData])

Setters in any react hooks are asynchronous.任何反应钩子中的设置器都是异步的。 React under the hood sets the state and fires the events to re-render the component or any change that depends on this state, all of it but asynchronously. React 在后台设置状态并触发事件以重新渲染组件或任何依赖于该状态的更改,所有这些都是异步的。

setArrData sets the data but to read the updated data, you should use useEffect hook for above-mentioned reason. setArrData设置数据,但要读取更新的数据,由于上述原因,您应该使用useEffect钩子。

useEffect(()=>
    console.log(arrData); <-- on first render the value here will be what you have assigned while defining the state i.e. [] in this case.
}, [arrData]) <--- this is dependency array, 
                   that tell this *useEffect* to run when *arrData* state changes

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

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