我无法在回调axios中更改状态(我使用过useEffect,useState,axios)

时间:2019-11-19 11:32:03

标签: reactjs axios react-hooks

function User() {
    const [user, setUser] = useState({})

    useEffect(() => {
        const user-token = window.localStorage.getItem('user-token');
        const getUser = async () => {
        if (user-token !== null) {
            const user = await axios.get('http://localhost:5000/api/index/info')

            setUser(user.data.info)
            console.log(user.data.info) // server return result is what I expected: {name: "hanh", age: 20}
            console.log(user) // but this is not change, it still {} 
        }

        getUser()
    }, []
}

3 个答案:

答案 0 :(得分:2)

这是因为setUser异步运行,并且console.log(user)在状态更新之前已执行。

您可以使用useEffect来检查状态是否已更新。

例如:

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

用户每次更改都会执行效果

如果每次状态更改时都希望有一个回调,则可以编写如下的customHook

function useStateWithCallBack(initlaValue, callBack) {
  const [state, setState] = useState(initlaValue);
  useEffect(() => callBack(state), [state]);
  return [state, setState];
}

您可以在this沙箱中找到此类customHook的有效示例:

答案 1 :(得分:0)

删除这些

console.log(user.data.info)
console.log(用户)

添加此

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

function User() {
    const [user, setUser] = useState({})

    useEffect(() => {
        const user-token = window.localStorage.getItem('user-token');
        const getUser = async () => {
        if (user-token !== null) {
            const user = await axios.get('http://localhost:5000/api/index/info')

            setUser(user.data.info)
        }


    }, []);

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

}

答案 2 :(得分:0)

function User() {
    const [userState, setUserState] = useState({})

    useEffect(() => {
        const userToken = window.localStorage.getItem('userToken');
        const getUser = async () => {
        if (userToken !== null) {
            const user = await axios.get('http://localhost:5000/api/index/info')

            setUserState(user.data.info)
            console.log(user.data.info) // server return result is what I expected: {name: "hanh", age: 20}
        }
        getUser()
    }, [])

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

或类似下面的内容,如果其他地方使用userInfo

function User() {
    const [userState, setUserState] = useState({})
    const userRef = useRef({})

    useEffect(() => {
        const userToken = window.localStorage.getItem('userToken');
        const getUser = async () => {
        if (userToken !== null) {
            const user = await axios.get('http://localhost:5000/api/index/info')

            setUserState(user.data.info)
            userRef.current = user.data.info // somewhere else can acquire userinfo by userRef.current
            console.log(userRef.current)
        }
        getUser()
    }, [])
}