【问题标题】:Error 400 and 200 with useEffect React Hook使用 useEffect React Hook 时出现错误 400 和 200
【发布时间】:2021-09-02 23:33:08
【问题描述】:

我有一个 API,带有 Node 和 MongoDB。

我对这个请求做了以下组件:

export default function Balance() {
    const uid = useContext(UidContext)

    useEffect(() => {
        axios({
            method: "get",
            url: `${process.env.REACT_APP_API_URL}api/balance/${uid}`
        }).then(response => console.log(response.data[0]));
    }, [uid]);

    return (
        <section>
            Walet
        </section>
    )
}

我得到一个错误,我想要的结果: Result

我不明白为什么我得到一个错误,然后是代码 200 ?

谢谢!

【问题讨论】:

    标签: reactjs api axios react-hooks use-effect


    【解决方案1】:

    这是因为您的uid 起初为空。你可以做一个 null 检查:

      useEffect(() => {
          if(uid !== null){
            axios({
                method: "get",
                url: `${process.env.REACT_APP_API_URL}api/balance/${uid}`
            }).then(response => console.log(response.data[0]));
           }
        }, [uid]);
    
    

    【讨论】:

    • 我怎么没想到?!谢谢!
    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2019-10-08
    • 2022-11-23
    • 2020-06-07
    • 2021-11-23
    • 1970-01-01
    相关资源
    最近更新 更多