React - 重置从 axios fetch 存储的状态

React - Reset State stored from axios fetch

在我从数据库中删除后,我试图通过单击 handleDelete 来重置存储在我的 users 数组中的对象的状态。但是,我的状态没有改变。我可以使用 console.log('found: ' + this.state.users[i]) 登录当前用户。基本上,我从我的 API 中填充了一个 table,我试图在不刷新页面的情况下删除状态行,但状态没有更新。

存储我的初始状态的构造函数:

  constructor(props) {
    super(props);
    this.state = {
      users: []
    }
    this.handleDelete = this.handleDelete.bind(this);
  };

在挂载上获取 API:

  componentDidMount() {
    fetch('/myAPI')
      .then(res => res.json())
      .then(users => this.setState({ users }));
  }

映射存储在 fetch 状态中的数据

  render() {
    return (
      <tbody>
        {this.state.users.map(user =>
          <tr key={user.uniqueid}>
            <td>{user.name}</td>
            <td>{user.versions}</td>
            <td>{user.type}</td>
            <td>{user.hours}</td>
            <td>{user.refresh}</td>
            <td>{user.uniqueid}</td>
            <td>{user.date}</td>
            <td><Button onClick={this.handleDelete} data-id={user.uniqueid}><FaTrashO /></Button></td>
          </tr>
        )}
      </tbody>
    );
  }

删除我正在尝试重置状态的处理程序:

  handleDelete(e) {
    let dataId = e.target.getAttribute('data-id');

    axios({
      method: 'delete',
      responseType: 'json',
      url: '/myAPI',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Methods': "GET,HEAD,OPTIONS,POST,PUT"
      },
      data: { _id: dataId }
    })
    .then((response) => {
      console.log(dataId + ' deleted with axios')

      for (let i = 0; i < this.state.users.length; i++){
        if (dataId === this.state.users[i]._id) {

          let currentObj = this.state.users[i];
          console.log('found: ' + this.state.users[i])

          this.setState((prevState) => {
            currentObj._id = ''
            currentObj.date = '',
            currentObj.hours = '',
            currentObj.name = '',
            currentObj.refresh = '',
            currentObj.type = '',
            currentObj.uniqueid = '',
            currentObj.versions = ''
          });
        }
      }
    })
    .catch((err) => {
      throw err;
    })
  }

我从 API 呼叫的示例:

[
{
_id: "XJAbmHCX",
name: "an_example_2",
type: "B",
versions: "10",
hours: "10",
refresh: "Yes",
uniqueid: "XJAbmHCX",
date: "2018/01/08",
__v: 0
},
{
_id: "TOoIi7xS",
name: "test",
type: "A",
versions: "10",
hours: "10",
refresh: "Yes",
uniqueid: "TOoIi7xS",
date: "2018/01/09",
__v: 0
},
{
_id: "oeaigjesroigj",
name: "an_example_2_1",
type: "B",
versions: "10",
hours: "10",
refresh: "Yes",
uniqueid: "oeaigjesroigj",
date: "2018/01/08",
__v: 0
}
]

handleDelete的for循环中,我简单的对user进行了切片,将每一个没有当前ID的对象都返回给state

for (let i = 0; i < this.state.users.length; i++){
        if (dataId === this.state.users[i]._id) {
          let users = this.state.users.slice();
          users = users.filter(u => { return u._id !== dataId; });
          this.setState({ users: users });

        }
      }