Javascript 如何在呈现组件之前更新状态?
我有一个应用程序,可以在“电话簿”中添加“个人”,如果此人已经存在,用户可以更新此人的手机。 但我想知道如何处理这个人何时被删除的问题(我打开两个选项卡,在一个选项卡中删除一部手机,然后在第二个选项卡中尝试“更新”它) 我有一个Javascript 如何在呈现组件之前更新状态?,javascript,reactjs,axios,react-hooks,setstate,Javascript,Reactjs,Axios,React Hooks,Setstate,我有一个应用程序,可以在“电话簿”中添加“个人”,如果此人已经存在,用户可以更新此人的手机。 但我想知道如何处理这个人何时被删除的问题(我打开两个选项卡,在一个选项卡中删除一部手机,然后在第二个选项卡中尝试“更新”它) 我有一个persons.js,它处理所有HTTP请求(我使用的是axios) 还有一个PersonNotification.js,告诉用户手机是否“添加”或“更新”或“不再存在” 所有主要功能都在App.js 这是我的密码 persons.js import axios from
persons.js
,它处理所有HTTP请求(我使用的是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 };
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
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;
const updatePerson = (person, number) => {
const request = axios
.put(`${URL}/${person[0].id}`, {
name: person[0].name,
number,
});
return request.then(response => response.data)
};
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
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 };
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
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;
const updatePerson = (person, number) => {
const request = axios
.put(`${URL}/${person[0].id}`, {
name: person[0].name,
number,
});
return request.then(response => response.data)
};
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("");
}
PersonNotification.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 };
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
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;
const updatePerson = (person, number) => {
const request = axios
.put(`${URL}/${person[0].id}`, {
name: person[0].name,
number,
});
return request.then(response => response.data)
};
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("");
}
从“React”导入React;
导入“/PersonNotification.css”;
const PersonNotification=({notification,errMsg})=>{
如果(errMsg.length>0){
返回{通知};
}
如果(notification.length==0){
返回;
}否则{
返回{通知};
}
};
导出默认人员通知;
附言:
这是此应用程序的文件夹。
这是一个来自fullstackopen.com的练习,所以我在这里发帖之前有点犹豫,但我花了4个多小时来解决这个问题
我只想弄清楚如何更早地更新“errMsg”的状态,我想在那之后一切都会变得很简单这一部分应该可以帮助您更进一步 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 };
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
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;
const updatePerson = (person, number) => {
const request = axios
.put(`${URL}/${person[0].id}`, {
name: person[0].name,
number,
});
return request.then(response => response.data)
};
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
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 };
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
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;
const updatePerson = (person, number) => {
const request = axios
.put(`${URL}/${person[0].id}`, {
name: person[0].name,
number,
});
return request.then(response => response.data)
};
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("");
}
你的问题是什么?连我都不太清楚你想知道什么?但是如果你关心的是当一个联系人已经从列表中删除,而其他人又试图再次删除它时该怎么办,然后,您可以对删除操作发出服务请求,并从后端发送适当的响应,说明此联系人已不存在,最后在UI上显示适当的消息,说明此联系人已被删除。否,我希望“personNotification”在屏幕上呈现“错误”。我想这正是我所需要的,因为我无法在app.js中捕捉到错误!抱歉,我没有看到您的更新。我现在已经对App.js做了很多更改,但我会检查一下您的更新,谢谢先生!哇,谢谢你,我从没想过要改变捕获物的状态。你真的救了我的命。我真是太感谢你了!