首页 > 解决方案 > Best way to update component after this handleClick?

问题描述

I currently have this function in a component. It requests a delete to an api. At the end of the function however I need to update the component so that the app re-renders the display thus removing a jsx element that rendered the object that was deleted. I know forceUpdate() is not recommended but it doesn't work in this code anyway. Anyone know why? And what is the better way to implement this component update? The backend is indeed deleting the requested object and the console log works btw.

  handleClick() {
    const logId = this.props.log._id;  
    fetch(`/api/logs/${logId}`, {
      method: 'DELETE',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },  
      body: JSON.stringify({
        id: logId
      })
    })
      .then(res => res.text())
      .then(res => alert(res))
      .catch(err => alert(err))  
    this.forceUpdate()
    console.log('Deleted log"')
  }

标签: reactjs

解决方案


为什么不使用 just setState?它会自动重新渲染您的组件。

.then((res) => this.setState({ deletedId: logId }))

然后您可以通知用户指定logId的已删除。

{this.state.deletedId && <span>deleted id: {this.state.deletedId}</span>}

推荐阅读