【发布时间】:2020-02-10 02:27:22
【问题描述】:
发布请求后,数据进入数据库,但不会重新渲染组件。我需要手动按下 F5 按钮,新的数据就会显示出来。 then 似乎没有执行。
class AddForm extends Component {
constructor(props) {
super(props)
this.state = {
id: null,
title: "",
price: 0,
pages: 0,
};
}
postData() {
const { title, price, pages } = this.state
const curTitle = title
const curPrice = price
const curPages = pages
fetch("api/books", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
Title: title,
Price: price,
NumberOfPages: pages
})
}).then(res => res.json()).then(() => this.setState({ title: curTitle, price: curPrice, pages: curPages }))
}
}
编辑: 当我执行以下操作时:
.then(response => response.json()).then(res => console.log(res))
我收到Uncaught (in promise) SyntaxError: Unexpected end of JSON input
【问题讨论】:
-
什么时候调用 postData 函数?
-
如果在
then()中添加console.log()而不是this.setState()会发生什么? -
@HadiRanjbar,当我在表单中按
handleSubmit时。 -
@norbitrial,当我这样做时:
.then(response => console.log(response)),我得到Unexpected end of JSON input -
查看这篇文章,可能对你有帮助:stackoverflow.com/questions/43362431/…
标签: javascript reactjs