【问题标题】:In React 18, when I am sending data to nodejs server, it is sending two request and receiving two response from server在 React 18 中,当我向 nodejs 服务器发送数据时,它正在发送两个请求并从服务器接收两个响应
【发布时间】:2022-07-24 01:37:24
【问题描述】:

这是用于向服务器站点发送访问令牌的前端代码。

useEffect(() => {
        const getProducts = async () => {
            try {
                const url = `http://localhost:5000/product?email=${user.email}`
                const { data } = await axios.get(url, {
                    headers: {
                        authorization: localStorage.getItem('accessToken')
                    }
                });
                setProducts(data);
            } catch (err) {
                const status = err.response.status;
                if (status === 401 || status === 403) {
                    signOut(auth);
                    navigate('/login');
                    localStorage.removeItem('accessToken')
                    toast.error(err.response?.data?.message);
                }
            }
        }
        getProducts();
    }, [user.email]);

这是用于响应的服务器站点快速代码。为什么每次接收两个请求,发送两个响应?

app.get('/product', verifyToken, async (req, res) => {
            const decoded = req.decoded?.email;
            const queryEmail = req.query?.email;
            if (decoded === queryEmail) {
                const query = { email: queryEmail };
                const cursor = medicineCollection.find(query);
                const products = await cursor.toArray();
                res.send(products);
            } else {
                res.status(403).send({ message: "Forbidden Access" })
            }

        })

【问题讨论】:

  • 看起来是其他东西触发了这种行为,为什么当user.email 发生变化时你会提出这个请求?请提供一些有关它的上下文并包括组件的代码。
  • 在 React 18 中,useEffect 渲染了两次,即使我清空了 useEffect 挂钩的依赖数组。
  • 看看this question,这个问题好像是严格模式造成的。

标签: node.js nodejs-server


【解决方案1】:

也许您将 user.email 置于某种正在更新的状态,这就是为什么 useEffect 再次调用并给您两次响应的原因。

【讨论】:

    猜你喜欢
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    相关资源
    最近更新 更多