【问题标题】:useEffect is not working the way i expect it touseEffect 没有按我期望的方式工作
【发布时间】:2022-08-17 22:50:44
【问题描述】:

我知道为什么,但我的 useEffect 发生了两次,它弄乱了我的代码:(

useEffect(() => {
axios
  .post(\"/register\", {
    fullname,
    username,
    email,
    password,
  })
  .then((response) => {
    setMessage(JSON.stringify(response.data.success));
    console.log(message);
    if (message === \"true\") {
      setOpen(true);
      setTimeout(() => {
        navigate(\"/signin\");
      }, 3000);
    } else {
      setErrorMessage(
        JSON.stringify(Object.keys(response.data.msg.keyPattern)[0])
      ); //TODO: create better validation message
    }
  })
  .catch((error) => {
    return error;
  });
}, [email, fullname, message, navigate, password, username]);

我对 API 调用有点陌生。 我试图实现的是从服务器获得成功消息的响应, 如果它是真的有我想打开的小吃店,然后导航到登录。 如果成功消息为假,我想提醒一个错误。

我认为由于 useEffect 而发生的另一个问题是,即使我有唯一的电子邮件属性和用户属性,它也会不止一次地保存在数据库中。

  • 必须在后端限制数据库中的数据重复.. 在将 newUser 加入数据库之前,您必须检查用户是否存在...关于 useEffect,您有很多依赖项,因此很难判断哪个状态变量导致api重复..
  • 阅读 React.StrictMode 以了解为什么它被调用两次

标签: reactjs mongodb api mongoose


【解决方案1】:

这可能是因为严格模式。试试这个并检查它是否有效。 用 <React.StrictMode> 包装一切

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { MainPage } from './pages/MainPage';


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <MainPage />
  </React.StrictMode>
);

【讨论】:

  • 我已将 app.js 添加到我的帖子中。我已经用它包装了我的应用程序。
猜你喜欢
  • 2022-12-13
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多