【发布时间】:2018-12-11 04:01:39
【问题描述】:
我使用 fetch API 从表单中发布一些数据,这很有效。
但是我遇到了一个问题,问题是当我发布数据时状态不会更新,是的,我知道我没有使用 setState(),但没有任何设置。还没有。
目前我正在尝试通过控制台日志来调试问题,结果发现主体没有被使用。
提交函数:
addContact = (event) => {
event.preventDefault(); //Prevents The Default Action Of A Form
const formData = {};
/*
for(let [temp variable] in this.state.contacts) {
formData[attach temp variable] = to contacts[temp variable].value
}
*/
// BASIC TERM: For everything in the contacts config set the formData (Blank Object) equal to the identifier e.g. name, street equal to the state value. The object will then be populated
// The formData is then attached to an object named object and sent to the firebase database by attaching it to the post request
for(let formElementIdentifier in this.state.contacts) {
formData[formElementIdentifier] = this.state.contacts[formElementIdentifier].value;
}
const data = {
persons: formData
}
fetch("https://address-book-database.firebaseio.com/contact.json", {
method: "POST",
headers : {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then((res) => {
console.log("Body Used Or Not")
console.log(res.bodyUsed)
})
.then(json => {
})
}
这是第一次使用 fetch API。 Tm 真的很困惑为什么这不起作用,任何帮助将不胜感激。我知道链接 .then() 但我无法让它与 POST requet 一起使用。
我要做的就是设置表单中的值并将其附加到请求中,请求需要转换为 JSON,然后需要更新状态。
【问题讨论】:
-
尝试直接在
this.state.contacts上使用JSON.stringify并发送它。还可以在获取后从您的第一个then返回res.json(),看看您会得到什么。 -
所以看起来 name 只能被访问,即使整个状态都被提交到数据库。
标签: javascript reactjs