在此组件中,9 John
6 Wad
3 William
在触发异步onSubmit函数后不起作用。
John 9
Wad 6
William 3
答案 0 :(得分:0)
我认为在函数内分解props并不是一个好主意,它应该在render方法内。这是我尝试模拟您要执行的操作。
import React, { Component } from "react";
const name = "Mathew";
export default class StackOverflow extends Component {
constructor(props) {
super(props);
this.state = {
addingProduct: false,
server: []
};
this.addProductToServer = this.addProductToServer.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
addProductToServer(data) {
return this.state.server.push(data);
}
async onSubmit(formData) {
this.setState({ addingProduct: true });
await this.addProductToServer(formData);
this.setState({ addingProduct: false });
}
render() {
// const { addProductToServer } = this.props
console.log("server", this.state.server);
console.log("addingProduct", this.state.addingProduct)
return (
<div>
<h3>Hello StackOverflow</h3>
<p>{this.state.server.map((item, index) => (
<li key = {index}>{item}</li>
))}</p>
<button onClick={() => this.onSubmit(name)} type="submit">
Submit
</button>
</div>
);
}
}
这有效。这就是sandbox
中的内容