我正在开发电话簿应用程序。我从表单中获取用户输入,然后将其添加到我的状态,然后在该状态上应用映射方法以获取用户详细信息。 这是我的代码:
import React, { useState, useEffect } from "react";
const phoneBook = [];
const App = () => {
const [contacts, setContacts] = useState(phoneBook);
const [showForm, setShowForm] = useState(false);
const [userName, setUserName] = useState("");
const [number, setNumber] = useState("");
const handleDelete = (name) => {
let newPhoneBook = contacts.filter((contact) => contact.name !== name);
setContacts(newPhoneBook);
};
const handleAddContact = (userName, number) => {
let obj = { name: userName, number: number };
console.log("obj:", obj);
phoneBook.push(obj);
console.log("contacts:", contacts);
console.log("phoneBook:", phoneBook);
};
return (
<div id="main">
<div className="container-fluid">
<div className="row">
<div className="col-md-4"></div>
<div className="col-md-4">
<div className="App">
<h2 className="header">PhoneBook App</h2>
<span
style={{
cursor: "pointer",
color: "blue",
textDecoration: "underline",
}}
onClick={() => setShowForm(!showForm)}
>
{showForm ? "Hide Contact Form" : "Create New Contact"}
</span>
{showForm && (
<div className="container">
<form className="form">
<div class="form-group">
<input
type="text"
className="form-control"
placeHolder="Name"
value={userName}
onChange={(e) => {
e.target.value;
setUserName(e.target.value);
console.log("userName:", userName);
console.log("e.target.value:", e.target.value);
}}
/>
</div>
<div class="form-group">
<input
type="text"
className="form-control"
placeHolder="Number"
value={number}
onChange={(e) => {
e.target.value;
setNumber(e.target.value);
console.log("number:", number);
console.log("e.target.value:", e.target.value);
}}
/>
</div>
<button
type="button"
className="btn btn-primary icon-holder"
onClick={() => {
handleAddContact(userName, number);
}}
>
Add
</button>
</form>
</div>
)}
<p>
There are {contacts.length} contacts saved in this book yet.
</p>
{contacts.map((contact, index) => (
<div key={index} className="contacts">
<div class="contact-details">
<h5>{contact.name}</h5>
<p>{contact.number}</p>
</div>
<button
class="icon-holder"
onClick={() => {
handleDelete(contact.name);
}}
>
Delete
</button>
<hr />
</div>
))}
</div>
</div>
<div className="col-md-4"></div>
</div>
</div>
</div>
);
};
export default App;
我面临的问题是 contacts 在控制台中显示更新的值,但没有通过地图方法在浏览器中显示。 我有线索表明存在 useState 问题,例如它如何影响渲染。我注意到的一件事是,如果我对代码进行任何更改,那么地图方法会显示当时保存的用户。
添加联系人时您正在改变状态: 改变
phoneBook
数组会改变 contacts
状态,但不会设置它,这意味着 React 不知道更改,也不会重新渲染新值。
抛弃
phoneBook
数组,直接设置contacts
状态。使用传播的联系人的先前值加上新联系人创建一个新数组。
const handleAddContact = (userName, number) => {
const contact = { name: userName, number: number };
// create a new contacts array that is combined from the previous values + the new contact
setContacts(prev => [...prev, contact]);
};