Невозможно выполнить обновление состояния React для отключенного функционального компонента, используя ax ios .post - PullRequest
0 голосов
/ 16 февраля 2020

при обработке userForm и вызове функции showUser из пользовательского компонента ..... получение сообщения: не удается выполнить обновление состояния React для неустановленного компонента.

Я пытался использовать монтировать свойство без успеха. Вот мой компонент userForm:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import {
  Button,
  Modal,
  FormGroup,
  FormControl,
  FormLabel
} from "react-bootstrap";
import axios from "axios";
import { useForm } from "react-hook-form";
import ReactInterval from "react-interval";

export default function UserForm(props) {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(true);
  if (props.data.first_name) setValue("nombres", props.data.first_name);
  if (props.data.email) setValue("email", props.data.email);
  if (props.data.empresa) setValue("empresa", props.data.empresa);
  if (props.data.password) setValue("password", props.data.password);

  const { register, handleSubmit, setValue, errors } = useForm();
  const [showMsg, setShowMsg] = useState(false);
  const [msg, setMsg] = useState();
  const [page, setPage] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  const [show, setShow] = useState(false);

  const onSubmit = data => {
    let mounted = true;
    const result = axios
      .post("http://www.localhost/avatar/api/saveUser", { data })
      .then(response => {
        console.log(response.data);
        if (mounted) {
          if (response.data == "success") {
            setShowMsg(true);
            setMsg("Registro completado");
            setInterval(() => {
              setShowMsg(false);
            }, 5000);
            props.showUsers(true);
          }
          if (response.data == "existing") {
            setShowMsg(true);
            setMsg("Email ya está registrado");

            $("#first_name").val(props.data.first_name);
            $("#email").val(props.data.email);
            $("#empresa").val(props.data.empresa);
            setValue("email", data.email);
            setValue("id_ciudad", data.id_ciudad);
            if (data.id_profesion) setValue("id_profesion", data.id_profesion);
            if (data.empresa) setValue("empresa", data.empresa);
            if (data.password) setValue("password", data.password);
          }
        }
      })
      .catch(error => {
        if (mounted) {
          console.log(error);
        }
      });
    return () => (mounted = false);
  };

  if (loading) {
    <h2>Loading...</h2>;
  }
  return (
    <div className="container mt-5">
      <div className="row">
        <div className="col-xl-3 col-lg-4 col-md-6 col-sm-6 offset-4">
          <form onSubmit={handleSubmit(onSubmit)}>
            <input type="hidden" name="id" ref={register} />
            {showMsg && <p className="alert alert-danger mb-3">{msg}</p>}

            <FormGroup controlId="email">
              <FormLabel>
                email{" "}
                {errors.email && (
                  <span style={{ color: "Red" }}> requerido</span>
                )}
              </FormLabel>
              <FormControl
                autoFocus
                name="email"
                ref={register({ required: true })}
              />
            </FormGroup>
            <FormGroup controlId="name" bssize="large">
              <FormLabel>
                Nombres{" "}
                {errors.nombres && (
                  <span style={{ color: "Red" }}> required</span>
                )}{" "}
              </FormLabel>

              <FormControl name="first_name" ref={register} />
            </FormGroup>
            <FormLabel className="text-center">Información Opcional</FormLabel>
            <div className="row">
              <div className="col-md-6">
                <FormGroup controlId="empresa" bssize="large">
                  <FormLabel>Grupo</FormLabel>
                  <FormControl name="empresa" ref={register} />
                </FormGroup>
              </div>

              <input
                type="submit"
                value="Save"
                className="btn btn-lg btn-block login-button"
              />
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}

Вот мой компонент User:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import {
  Button,
  Modal,
  FormGroup,
  FormControl,
  FormLabel
} from "react-bootstrap";
import axios from "axios";
import { useForm } from "react-hook-form";
import "react-bootstrap-table-next/dist/react-bootstrap-table2.min.css";
import Pagination from "../components/Pagination";
import UserForm from "../components/UserForm";

export default function Users(props) {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const { register, handleSubmit, setValue, errors } = useForm();
  const [email, setEmail] = useState("");
  const [empresa, setEmpresa] = useState("");
  const [id_title, setId_title] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [data, setData] = useState({});
  const [first_name, setFirst_name] = useState("");

  const showUsers = stat => {
    console.log(stat);
    setShow(stat);
    console.log(show);
  };
  const addUser = dat => {
    setShow(false)(dat.first_name)
      ? setTitle("Editar Usuario")
      : setTitle("Nuevo Usuario");

    if (dat) {
      if (dat.first_name !== "") setShow(false);
      console.log(dat);
      setData(dat);
      setFirst_name(dat.first_name);
      setValue("id", dat.id);
      setValue("email", dat.email);
      setValue("id_ciudad", dat.id_ciudad);
      if (dat.password) setValue("password", dat.password);
    }
  };

  if (loading) {
    <h2>Loading...</h2>;
  }
  return (
    <div className="container mt-5">
      <div className="row">
        <div className="col-md-6">
          <h1 className="text-primary mb-3">Usuarios</h1>
        </div>
        {title == "Nuevo Usuario" && (
          <div className="col-md-3">
            <p className="text-primary mb-3"> {title}</p>
          </div>
        )}
        {title == "Editar Usuario" && (
          <div className="col-md-3">
            <p className="text-primary mb-3"> {title}</p>
          </div>
        )}
        {title == "" && (
          <div className="col-md-3">
            <button onClick={addUser}>Agregar Usuario</button>
          </div>
        )}
        {(title == "Nuevo Usuario" || title == "Editar Usuario") && (
          <div className="col-md-3">
            <button onClick={cancelar}>Cancelar</button>
          </div>
        )}
      </div>
      {!show && <UserForm data={data} showUsers={showUsers} />}
      {show && (
        <div>
          <table className="table table-striped tableProd2">
            <thead>
              <tr>
                <th>Email</th>
                <th>Nombre</th>
                <th>Apellido</th>
                <th />
                <th />
              </tr>
            </thead>
            <tbody>
              {currentUsers.map(user => (
                <tr key={user.id}>
                  <td> {user.email} </td>
                  <td> {user.first_name} </td>
                  <td> {user.last_name} </td>
                  <td>
                    <a
                      onClick={() => {
                        addUser(user);
                      }}
                    >
                      <img
                        className="userImg"
                        src={
                          "http://www.localhost/avatar/public/images/edit.jpg"
                        }
                        title="edit"
                      />
                    </a>
                  </td>
                  <td>
                    <a onClick={() => deleteUser(user.id)}>
                      <img
                        className="userImg"
                        src={
                          "http://www.localhost/avatar/public/images/delete.png"
                        }
                        title="delete"
                      />
                    </a>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
...