首页 > 解决方案 > 在 this.state 中添加数据以在另一个函数中使用

问题描述

我正在尝试在 reactJS 中创建一个删除方法。我的逻辑是从 api 获取数据,在 中使用该数据this.state并从 中调用它componentDidMount以删除数据。

我不知道如何在 this.state 上显示数据 ID,或者我可以删除它。

当我单击Delete按钮时,我收到错误TypeError: Cannot read property 'state' of undefined

有人有想法吗?

class DeleteForm extends Component { 
  constructor(props){
    super(props);

    this.state = {
      id: ''
    }
  }

  async componentWillMount() {
    const url = 'http://localhost:8080/zoom';
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
  }

  componentDidMount() {
    axios.delete(`http://localhost:8080/zoom/${this.state.id}`)
    .then(res => console.log(res.data));
  }

  render() {
    return(
      <button onClick={this.componentDidMount}>Delete</button>
    )
  }
}

标签: reactjs

解决方案


假设您在响应中有 id 。你可以这样做。

class DeleteForm extends Component { 
  constructor(props){
    super(props);

    this.state = {
      id: ''
    }
  }

  async componentDidMount() {
    const url = 'http://localhost:8080/zoom';
    const response = await fetch(url);
    const data = await response.json();

    this.setState({
      id: data.id
    })
  }

  delete = () =>  {
    axios.delete(`http://localhost:8080/zoom/${this.state.id}`)
    .then(res => console.log(res.data));
  }

  render() {
    return(
      {this.state.id && <button onClick={this.delete}>Delete</button>}
    )
  }
}

仅当设置了 id 时才会显示您的按钮。


推荐阅读