Javascript 反应JS+;获取API发布
我使用fetchapi发布表单中的一些数据,这很有效 但是我面临一个问题,问题是当我发布数据时,状态不会更新,是的,我知道我没有使用setState(),但没有设置它。然而 目前,我正试图通过控制台日志来调试这个问题,结果发现主体没有被使用 提交功能:Javascript 反应JS+;获取API发布,javascript,reactjs,Javascript,Reactjs,我使用fetchapi发布表单中的一些数据,这很有效 但是我面临一个问题,问题是当我发布数据时,状态不会更新,是的,我知道我没有使用setState(),但没有设置它。然而 目前,我正试图通过控制台日志来调试这个问题,结果发现主体没有被使用 提交功能: addContact = (event) => { event.preventDefault(); //Prevents The Default Action Of A Form const formData
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 => {
})
}
这是第一次使用fetchapi。我真的很困惑为什么这行不通,任何帮助都将不胜感激。我知道链接。then()但是我无法让它与POST requet一起工作
我所要做的就是从我的表单中设置值并将其附加到请求,请求需要转换为JSON,然后状态需要更新
完整项目:使用您的获取请求,如下所示。您需要使用response.json()。它等待主体加载 为什么response.json会返回承诺 因为当所有头都到达时,您会收到响应。调用.json()可以为尚未加载的http响应体提供承诺
尝试直接在
this.state.contacts上使用JSON.stringify
,然后发送。同样,从第一次返回res.json()
,然后在获取后返回,看看您得到了什么。因此似乎只能访问name,即使整个状态被提交到数据库中。添加访问控制标头后,即使所有值都被提交到firebase数据库中,我似乎也只能访问名称值。您收到了它的响应吗?请在this.state.contacts中显示您的值,示例json这是登录提交的表单:App.js:93 Alex Machin App.js:93AlexMachin1997@gmail.comApp.js:93 1212121221 App.js:113 JSON数据App.js:114{name:“-LGUXG4vFeQ8t7WQdax9”}name:“-LGUXG4vFeQ8t7WQdax9”proto:objectit出于某种原因记录firebase ID
fetch('https://address-book-database.firebaseio.com/contact.json', {
method: 'post',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(data)
}).then(function (response) {
return response.json(); //response.json() is resolving its promise. It waits for the body to load
}).then(function (responseData) {
//Do your logic
});