我有一個名為 data 的空狀態變數data: {},當我從后端收到一個 json 物件時,我希望空物件成為我通過后端傳入的物件。假設我從后端收到的 json 是這樣的:
{
"data": {
"keywords": {
"Mrs. Johnson": 87
},
"score": 67
}
}
如何使我的data變數this.state更新為此:
"data": {
"data": {
"keywords": {
"Mrs. Johnson": 87
},
"score": 67
}
}
所以我可以使用里面的分數來訪問元素this.state.data.data.score?
這是我的反應代碼:
class Test extends Component {
constructor() {
super()
this.state = {
data: {}
}
}
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
body: JSON.stringify(this.state.text) // Irrelevant
};
console.log("hi")
fetch("http://127.0.0.1:5000/", options)
.then(response=> response.text())
.then(json => this.setState({data: json})) // This doesn't work
}
uj5u.com熱心網友回復:
您希望將回應決議為 json 物件而不是文本:
fetch("http://127.0.0.1:5000/", options)
.then(response=> response.json()) //notice the change here
.then(json => this.setState({data: json}))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417439.html
標籤:
