reactjs - 在 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>
)
}
}
解决方案
假设您在响应中有 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 时才会显示您的按钮。
推荐阅读
- clojure - 为什么 Lisp 允许替换 let 中的数学运算符?
- c# - 如何修复返回 -1 的 Select 语句
- php - 块大小无效:尝试安装 PEAR 时为 240
- java - 将 File 对象转换为路径包含空格的 URI 对象
- xamarin - 如何在 xamarin iOS 的 UITextView 中为 UIReturnKeyType.Done 创建操作
- python - AttributeError:“kivy.properties.ObjectProperty”对象没有属性“文本”
- bazel - 巴泽尔布德
:“可配置属性“实际”与此配置不匹配” - python - 如何更正输入框的输出
- html - 背景图像:当您通过快速应用程序打开 html 时,url() 不起作用
- spring - 如何处理 Spring WebClient 获取 application/octet-stream 作为 body InputStream?