【问题标题】:React - Reset State stored from axios fetchReact - 从 axios fetch 中存储的重置状态
【发布时间】:2018-06-19 00:02:42
【问题描述】:

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

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

  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 中映射存储在 state 中的数据

  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
}
]

【问题讨论】:

    标签: javascript json reactjs fetch axios


    【解决方案1】:

    handleDelete的for循环中,我只是简单地对用户进行了切片,并将没有当前ID的所有对象返回到状态

    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 });
    
            }
          }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-16
      • 2020-11-28
      • 2020-01-29
      • 1970-01-01
      • 2021-09-26
      • 2017-06-11
      • 1970-01-01
      • 2021-07-22
      相关资源
      最近更新 更多