【问题标题】:how to update the state before rendering the component?如何在渲染组件之前更新状态?
【发布时间】:2021-01-18 22:30:20
【问题描述】:

我有一个将“人员”添加到“电话簿”的应用程序,如果此人已经存在,用户可以更新此人的电话。 但我想知道处理此人何时已被删除的问题(我打开两个选项卡并在一个选项卡中删除一部手机,然后我尝试在第二个选项卡中“更新”它)

我有一个处理所有 HTTP 请求的persons.js(我正在使用 axios) 和 PersonNotification.js 告诉用户手机是“添加”、“更新”还是“不再存在” 所有主要功能都在App.js

这是我的代码

persons.js

import axios from "axios";
const URL = "http://localhost:3001/persons";

const getPersons = () => {
  return axios.get(URL).then((res) => res.data);
};

const addPerson = (person) => axios.post(URL, person);
// this is where i have the probelm (i think)
const updatePerson = (person, number, setErrMsg) => {
  axios
    .put(`${URL}/${person[0].id}`, {
      name: person[0].name,
      number,
    })
//i wanted the change the state of the App.js from this line after there is an error
    .catch((err) => setErrMsg("err"));
};

const deletePerson = (person) => axios.delete(`${URL}/${person.id}`);

export { getPersons, addPerson, deletePerson, updatePerson };

App.js

import React, { useState, useEffect } from "react";
import {
  getPersons,
  addPerson,
  deletePerson,
  updatePerson,
} from "./services/persons";
import Filter from "./components/Filter";
import Form from "./components/Form";
import Phonebook from "./components/Phonebook";
import PersonNotification from "./components/PersonNotification";
const App = () => {
  const [persons, setPersons] = useState([]);
  const [newName, setNewName] = useState("");
  const [newNumber, setNewNumber] = useState("");
  const [query, setQuery] = useState("");
  const [searchValue, setSearchValue] = useState([]);
  const [notification, setNotification] = useState("");
  const [errMsg, setErrMsg] = useState("");

  // fetching the data from json-server (i,e: db.json)
  useEffect(() => {
    getPersons().then((res) => setPersons(res));
  }, []);
  // function that fires after the submit
  const personsAdder = (e) => {
    e.preventDefault();
    const personsObject = { name: newName, number: newNumber };

    //checking if the name exists
    const nameChecker = persons.filter(
      (person) => person.name === personsObject.name
    );
    console.log(errMsg);
    if (nameChecker.length > 0) {
      const X = window.confirm(
        `${personsObject.name} already exists do you want to update the number`
      );

      if (X === true) {
        // updating the number if the user confirmed
        updatePerson(nameChecker, newNumber, setErrMsg);
        const personsCopy = persons;
        const index = personsCopy.indexOf(nameChecker[0]);
        personsCopy[index] = {
          id: personsCopy[index].id,
          name: personsCopy[index].name,
          number: newNumber,
        };

        setPersons([...personsCopy]);
        setNewName("");
        setNewNumber("");
        //the function the shows the notification for 5 seconds after the content was updated
        const notificationSetter = () => {
          let X = "";
          if (errMsg.length > 0) {
            X = `you can't update${nameChecker[0].name} because it doesn't exist anymore`;
          } else {
            X = `${nameChecker[0].name} was updated`;
          }
          setNotification(X);

          setTimeout(() => {
            setNotification("");
            setErrMsg("");
          }, 5000);
        };
        notificationSetter();
      }
    } else {
      //adding a new user if the name was not already in the phonebook
      setPersons(persons.concat(personsObject));
      addPerson(personsObject);
      setNewName("");
      setNewNumber("");
      //the function the shows the notification for 5 seconds after the content was added
      const notificationSetter = () => {
        setNotification(`${personsObject.name} was added`);
        setTimeout(() => {
          setNotification("");
        }, 5000);
      };
      notificationSetter();
    }
  };

//... there is still more down here; i don't know if i should copy paste all my code

PersonNotification.js

import React from "react";
import "./PersonNotification.css";

const PersonNotification = ({ notification, errMsg }) => {
  if (errMsg.length > 0) {
    return <h1 className="err">{notification}</h1>;
  }
  if (notification.length === 0) {
    return <></>;
  } else {
    return <h1 className="notification">{notification}</h1>;
  }
};

export default PersonNotification;

PS: 这是此应用程序的github 文件夹。 这是来自 fullstackopen.com 的一个练习,所以我在这里发布我的问题之前有点犹豫,但我在这个问题上花了 4 个多小时 我只想弄清楚如何更早地更新“errMsg”的状态,我认为之后一切都会变得容易

【问题讨论】:

  • 你的问题是什么?
  • 连我都不太清楚你想知道什么?但是,如果您关心的是当联系人已从列表中删除并且其他人试图再次删除它时该怎么办,那么您可以在删除操作上发出服务请求并从后端发送此联系人不存在的正确响应并最终在 UI 上显示该联系人已被删除的正确消息。
  • 不,我想让“personNotification”在屏幕上呈现“错误”。上面写着“此组件已被删除”

标签: javascript reactjs axios react-hooks setstate


【解决方案1】:

这部分应该可以帮助你走得更远。

persons.js

const updatePerson = (person, number) => {
  const request = axios
    .put(`${URL}/${person[0].id}`, {
      name: person[0].name,
      number,
    });
  return request.then(response => response.data)
};

App.js

if (X === true) {
  const notificationSetter = (X) => {
    setNotification(X);

    setTimeout(() => {
      setNotification("");
      setErrMsg("");
    }, 5000);
  };
  // updating the number if the user confirmed
  updatePerson(nameChecker, newNumber, setErrMsg)
  .then(data => {
    notificationSetter(`${nameChecker[0].name} was updated`);
    console.log('persons :>> ', persons);
    console.log('data :>> ', data);
    
    const personsCopy = persons;
    const index = personsCopy.indexOf(nameChecker[0]);
    personsCopy[index] = {
      id: personsCopy[index].id,
      name: personsCopy[index].name,
      number: newNumber,
    };
    
    setPersons([...personsCopy]);
  })
  .catch(error => {
    notificationSetter(`you can't update ${nameChecker[0].name} because it doesn't exist anymore`);
    getPersons().then((res) => setPersons(res));
  })
  setNewName("");
  setNewNumber("");
}

【讨论】:

  • 我认为这就是我所需要的,因为我无法在 app.js 中发现错误!
  • 对不起,我没有看到你的更新。我现在对我的 App.js 进行了很多更改,但我会检查你的更新,谢谢先生!
  • 哇,谢谢,我从没想过只改变 catch 内的状态。你真的救了我发疯。真是太感谢你了!
猜你喜欢
  • 2020-03-04
  • 2019-08-04
  • 2022-06-30
  • 1970-01-01
  • 2021-07-09
  • 2023-03-10
  • 2018-05-27
  • 1970-01-01
相关资源
最近更新 更多