简体   繁体   English

在 react.js 中,更新的 state 值未显示在表格列表中(表格列表使用 state 值)

[英]In react.js, updated state values aren't showing in table list( table list use state value )

I just made a table to display customers emails and added functions to remove or add new emails.我只是做了一个表格来显示客户的电子邮件,并添加了删除或添加新电子邮件的功能。 but for add function, I saved new email into state( users ).但是为了添加 function,我将新的 email 保存到状态( users )中。 but it's not showing in email table list.但它没有显示在 email 表列表中。 remove function is working great?删除 function 效果好吗? could you help me to fix this issue?你能帮我解决这个问题吗? Just attached my code刚刚附上了我的代码

import React, {useState} from 'react';

const Admin: NextPage = () => {

  const [users, setUsers] = useState([
    { email: "tomer@everything420.com" },
    { email: "roman.garilov.0309@gmail.com"},
  ]);

  const [email, setEmail] = useState('');

  const removeUser = rowEmail => {
    const updatedArray = users.filter((row) => row.email !== rowEmail);
    setUsers(updatedArray);
  }

  const addUser = () => {
    console.log(email);
    const lists = users;
    lists.push({'email' : email});
    setUsers(lists);
  }
  
  return (
    <>
    <div className="user-user">
      <input type="email" onChange={event => setEmail(event.target.value)} />
      <span onClick={() => addUser()}>Add User</span>
    </div>
    <div className="user-list">
      <table>
        <thead>
          <tr>
            <th>Users</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {users.map((val, key) => {
            return (
              <tr key={key}>
                <td>{val.email}</td>
                <td><span onClick={() => removeUser(val.email)}>Remove</span></td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
    </>
  );
}
  
export default Admin;

The line const lists = users;const lists = users; does not create a new array.不创建新数组。 It just creates a new variable that points to the same array.它只是创建一个指向同一个数组的新变量。 So the lists.push({'email': email});所以lists.push({'email': email}); will mutate the state, but in a way that react will not get notice of it.将突变 state,但以某种方式反应不会引起注意。

use利用

const lists = [...users];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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