我尝试用钩子调用请求post。首先,调用请求post使用这个。setState,它工作正常但是我想用钩子(useState)而不是setState,它不起作用
下面的代码正常运行
export default class AddShoes extends Component {
constructor(props) {
super(props);
this.state = this.startValue;
this.state.show = false;
this.shoesChange = this.shoesChange.bind(this);
}
startValue = {
brand: "",
model: "",
date: "",
price: "",
img: "",
};
shoesChange = (event) => {
this.setState({
[event.target.name]: event.target.value,
});
};
submitShoes = (event) => {
event.preventDefault();
const shoes = {
brand: this.state.brand,
model: this.state.model,
date: this.state.date,
price: this.state.price,
img: this.state.img,
};
axios.post("http://localhost:8080/api", shoes).then((response) => {
if (response.data != null) {
this.setState(this.startValue);
alert("added")
}
});
};
下面的第二段代码不起作用
export default function AddShoes() {
const [values, setValues] = useState({
brand: "",
model: "",
date: "",
price: "",
img: "",
});
// const [show, setShow] = useState(false);
const handleSetInputs = (e) => {
setValues({ ...values, [e.target.name]: e.target.value });
};
const submitShoes = (event) => {
event.preventDefault();
axios.post("http://localhost:8080/api", values)
.then((response) => {
if (response.data != null) {
setValues(response.data);
alert("added!");
}
});
};
我应该改变什么?
要在React Hooks中更改状态对象的一个属性,您必须这样做:
setValues(prevValues => ({ ...prevValues, [e.target.name]: e.target.value }));
在第一个有效的例子中,您通过调用this.setState(this.startValue)
来重置状态在第二个示例中,您在setValuesetValues(response.data)
中传递网络请求的结果在AddShoes
函数组件之外创建initialValues
。
const initialValues = {
brand: "",
model: "",
date: "",
price: "",
img: "",
}
现在将其传递给submitShoes
中的setValues
const submitShoes = (event) => {
event.preventDefault();
axios.post("http://localhost:8080/api", values)
.then((response) => {
if (response.data != null) {
setValues(initialValues);
alert("added!");
}
});
};