无法使用React JS中的挂钩在状态上按时设置数据

问题描述

我正在从事Instagram克隆项目。我正在做个人资料页面的一部分,但遇到了一些问题。 我正在尝试使用挂钩(useState)来设置服务器上带有用户文档的响应。我的问题是,当我使用useEffect(仅与[]一起使用一次)时,未设置用户名状态。 我让useEffect无限运行,然后发现状态是在一段时间后设置的。

    const getUser = async () => {
        await axios.get(`/user/getbyusername/${props.match.params.username}`)
            .then(res => {
                console.log(res.data) // PRINTS DATA CORRECTLY
                setProfileUser({
                    _id: res.data._id,username: res.data.username,fullName: res.data.fullName,followersCount: res.data.followersCount,followingCount: res.data.followingCount,profileImage_PublicId: res.data.profileImage_PublicId,bio: res.data.bio
                })
                console.log(profileUser)
            })
    }
    // DOES NOT SET ANY DATA
    useEffect(() => {
        getUser(); // async function and awaits for the server response

        // HERE,I call getUserPosts using profileUser._id,and it profileUser._id is not set yet
        getPosts(); // async function as well
    },[])

检查setProfileUser(...)是否正确,这是因为它设置了数据,但是过了一段时间,即使我第一次可以使用[]正确地console.log(res.data)。>

    // WORKS,sets the user state after two runs. NOT GOOD PRACTICE
    useEffect(() => {
        getUser();
    })

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)