[英]re-render component after post request api react
發布請求后,數據進入數據庫,但不會重新呈現組件。 我需要手動按下 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
那么從您的問題來看,您似乎可以在提交時進行狀態更新,唯一的問題是關於顯示數據,為此我可能建議您放置另一個組件來顯示數據。 過去它對我有用。 只要讓我知道它是否對你有用。
res => res.json() :這給出了一個 JSON 響應,將此 JSON 響應值綁定到 setState 中的狀態。
希望您的回復如下所示,
response.data = {
curTitle: 'some title',
curPrice: 'some price',
curPages: 'some pages'
}
第二次更改您的 fetch 調用,然后功能如下,
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
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.