简体   繁体   中英

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. 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. 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(''); statement, you might wanted to use 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:

//                                            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:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM