[英]I am not able to add user input to state properly, getting map not a function error when it is
I have a simple list which is stored in the App component.我有一个简单的列表,它存储在 App 组件中。 This is used to display all the people and I want to be able to add new people to this list.
这用于显示所有人,我希望能够将新人添加到此列表中。 I am not able to add input into my state, I am getting an error that map is not a function.
我无法将输入添加到我的 state,我收到一个错误,即 map 不是 function。 Am i not creating the array properly?
我没有正确创建数组吗?
const App = () => {
const [persons, setPersons] = useState([
{
name: 'Artos Hellas',
id: 1
}
]);
const [newName, setNewName] = useState('');
const handleNewName = event => {
setNewName(event.target.value);
};
const addName = event => {
event.preventDefault();
const personObject = {
name: newName,
id: persons.length + 1
};
setPersons(persons.concat(personObject));
setPersons('');
};
const rows = () => persons.map(p => <li key={p.key}>{p.name}</li>);
return (
<div>
<h2>Phonebook</h2>
<form onSubmit={addName}>
<div>
name : <input value={newName} onChange={handleNewName} />
</div>
<div>
<button type="submit">add</button>
</div>
</form>
<h2>Numbers</h2>
<ul>{rows()}</ul>
</div>
);
};
Remove the setPersons('');
删除
setPersons('');
statement, you might wanted to use setNewName('')
:声明,您可能想使用
setNewName('')
:
const addName = event => {
event.preventDefault();
const personObject = {
name: newName,
id: persons.length + 1
};
setPersons(persons.concat(personObject));
// setPersons('');
setNewName('');
};
Also, you got a wrong key
prop while rendering list elements:此外,您在渲染列表元素时得到了错误的
key
prop:
// v Not p.key
const rows = () => persons.map(p => <li key={p.id}>{p.name}</li>);
Moreover, it's confusing when you use a function named row
and call it row()
, you may try naming it as an action like renderRows
or just use the ReactElement
array:此外,当您使用名为
row
的 function 并将其命名为row()
时,您可能会感到困惑,您可以尝试将其命名为类似renderRows
的操作,或者只使用ReactElement
数组:
const renderRows = () => persons.map(p => <li key={p.id}>{p.name}</li>);
<ul>{renderRows()}</ul>
// Or
const rows = persons.map(p => <li key={p.id}>{p.name}</li>);
<ul>{rows}</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.