单击按钮即可请求Axios

时间:2019-07-08 10:03:15

标签: reactjs axios

此功能与Postman一起使用时,为什么不从数据库中删除测验?

 deleteQuiz = () => {
    const quiz = this.state.quizData._id
     axios.delete(`http://localhost:5000/${quiz}`) 
    .then(res => {
      console.log(res.data)

  })

具有onClick:

<button onClick={() => this.deleteQuiz(this.state.quizData._id)}>Delete Quiz </button>

类似地,这不起作用:

topicSearch = topic => {
    axios.get(`http://localhost:5000/search/${topic}`)
        .then(res => {
            const data = res.data;
            this.setState({
                quizSelection: data
            })
        })
     }
}

在子组件中带有onClick,并传入topicSearch

 onClick={this.props.topicSearch}

但是当在onChangeHandler内调用topicSearch()并传递e.target.value时,确实可以工作

handleTopicChange = eventValue => {
    this.topicSearch(eventValue)
    this.setState({
        topic: topic
    })
}

从其他示例看来,将状态传递到函数中是可以接受的-这是我显然缺少的东西吗?

1 个答案:

答案 0 :(得分:0)

您在这里没有得到任何参数:

deleteQuiz = () => {
  const quiz = this.state.quizData._id;
  axios.delete(`http://localhost:5000/${quiz}`).then(res => {
    console.log(res.data);
  });
};

因此使用这样的参数:

deleteQuiz = quiz => {
  axios.delete(`http://localhost:5000/${quiz}`).then(res => {
    console.log(res.data);
  });
};

这将使用传递的参数,而不是来自状态的参数。

<button onClick={() => this.deleteQuiz(this.state.quizData._id)}> Delete Quiz </button>
相关问题