Javascript 请求后api反应后重新呈现组件
post请求后,数据进入数据库,但不会重新呈现组件。我需要手动按下F5按钮,新数据将显示出来。似乎Javascript 请求后api反应后重新呈现组件,javascript,reactjs,Javascript,Reactjs,post请求后,数据进入数据库,但不会重新呈现组件。我需要手动按下F5按钮,新数据将显示出来。似乎然后没有执行 class AddForm extends Component { constructor(props) { super(props) this.state = { id: null, title: "", price: 0, pages: 0,
然后
没有执行
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))
我得到未捕获(承诺中)语法错误:JSON输入意外结束
res=>res.JSON():这会给出一个JSON响应,将此JSON响应值绑定到setState中的状态
希望您的回复如下:
response.data = {
curTitle: 'some title',
curPrice: 'some price',
curPages: 'some pages'
}
constructor(props) {
super(props)
this.state = {
id: null,
title: "",
price: 0,
pages: 0,
};
this.postData = this.postData.bind(this); // Add this line, cannot read property error will be gone.
}
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((responseJson) => {
console.log(responseJson); // what is the output of this?
this.setState({
title: responseJson.data.curTitle,
price: responseJson.data.curPrice,
pages: responseJson.data.curPages
})
})
第二次更改fetch调用,然后执行如下操作
response.data = {
curTitle: 'some title',
curPrice: 'some price',
curPages: 'some pages'
}
constructor(props) {
super(props)
this.state = {
id: null,
title: "",
price: 0,
pages: 0,
};
this.postData = this.postData.bind(this); // Add this line, cannot read property error will be gone.
}
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((responseJson) => {
console.log(responseJson); // what is the output of this?
this.setState({
title: responseJson.data.curTitle,
price: responseJson.data.curPrice,
pages: responseJson.data.curPages
})
})
从您的问题来看,您似乎能够在提交时进行状态更新,唯一的问题是关于显示数据,因此我建议您放置另一个组件来显示数据。这在过去对我很有效。请告诉我它是否对您有效。当您调用postData函数时?如果您添加
console.log()
而不是this.setState()
中的then()
,我得到了意外的JSON输入结束
检查这篇文章,它可能会帮助你:我尝试了这个解决方案,但它没有显示新数据。console.log(响应)的输出是什么?在尝试我的解决方案时,你得到了任何错误吗?Uncaught(承诺中)SyntaxError:I console.log(response)在
处意外结束JSON输入,然后像上面那样更改第二个回调,并告诉我控制台打印的是什么?