我目前在更新我的ReactJS状态的对象数组时遇到问题,我无法弄清楚。我不想使用数据库或redux来进行响应。
如果userData数组中的Objects具有用于标识每个对象的键,那么我可以做类似userData [key] = data的操作。但是在这种情况下,我不知道如何在单击编辑按钮时访问传递给表单字段的确切对象。请帮忙。谢谢
这是我的代码。
//This is a contact management application
import React, { useState, useEffect } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import Home from "./components/Home";
import ContactPage from "./components/ContactPage";
import ContactForm from "./components/ContactForm";
import Nav from "./components/Nav";
import { Route, Switch, BrowserRouter } from "react-router-dom";
function App() {
const [data, setData] = useState({
firstName: "",
lastName: "",
phoneNumber: "",
email: "",
address: "",
imag: "",
});
// declear a new state varaible to store data
const [userData, setUserData] = useState(
JSON.parse(localStorage.getItem("userD")) || []
);
//declear a useEffect to store state locally on each change
useEffect(() => {
localStorage.setItem("userD", JSON.stringify(userData));
}, [userData]);
function handleChange(e) {
let name = e.target.name;
let value = e.target.value;
setData({
...data,
[name]: value,
});
}
/* Here is where I have a problem. onSubmit, I want to check all the contacts in the userData array, If it does not exist then push it there (Using the phoneNumber as a unique identifier). I cannot figure out how to update the exact same object in the array if the phoneNumber already exist in the userData array*/
function handleSubmit(data) {
let phoneNumberArr = userData.map((d) => d.phoneNumber);
if (phoneNumberArr.indexOf(data.phoneNumber) === -1) {
setUserData([...userData, data]);
}else {
}
setData({
firstName: "",
lastName: "",
phoneNumber: "",
email: "",
address: "",
imag: "",
});
}
function handleDelete(index) {
if (window.confirm("Click Ok if you want to delete or Cancle to exit")) {
setUserData(userData.filter((d) => userData.indexOf(d) !== index));
}
}
function handleEdit(info) {
setData({
firstName: info.firstName,
lastName: info.lastName,
phoneNumber: info.phoneNumber,
email: info.email,
address: info.address,
imag: info.imag,
});
}
function handleAddNew() {
setData({
firstName: "",
lastName: "",
phoneNumber: "",
email: "",
address: "",
imag: "",
});
}
答案 0 :(得分:0)
假设传递给data
的{{1}}参数是一个带有handleSubmit
键的对象,则很容易使用JavaScript的{{3}检查它是否存在于userData数组中。 }。
phoneNumber