我成功发送了一个发布请求,并且条目进入了数据库。我希望应用程序重新渲染以在表中显示新条目。但是setState会击中addForm变量,并且表单会消失,但不会再次重新呈现以显示新字符,我知道这是由于异步性造成的,只是不确定如何以正确的顺序进行工作。
到目前为止,我已经尝试过: -确保兑现诺言-行为没有改变
再次向setState添加第三个.then尝试强制重新渲染-行为不变
使用this.forceUpdate尝试强制-行为不变
所有研究都显示setState是解决此问题的方法,但没有成功。我现在想知道我的语法是错误的还是构造不正确。
获取请求
handleSubmit = (character) => {
console.log(character);
const url = "http://localhost:3000//api/v1/basics"
const body = JSON.stringify(
{ name: character.name,
age: character.age,
sex: character.sex,
classs: character.classs,
race: character.race,
height: character.height
})
fetch(url,{
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: body
}).then((res) =>{
return res.json();
}).then((res) => {
this.setState({ character: res })
}).then((res) => {
console.log(this.state);
this.setState({ addForm: false })
})
}
我希望该组件使用新条目重新呈现,但是在窗体关闭后不会发生任何重新呈现。如果我刷新页面,则页面会更新,但不会单击。
编辑1 .:完整的组件,我知道这很混乱,这是一个带有反应的游戏,请看它的作用。
import React, { Component } from 'react';
import Table from './Table'
import SimpleCharacterInfoForm from './SimpleCharacterForm'
import CharacterSkillsForm from './characterSkillsForm'
import './App.css'
export default class App extends Component {
state = {
addForm: false,
editForm: false,
character: []
}
addCharacter = () => {
this.setState({
addForm: true
})
}
removeCharacter = index => {
const url = `http://localhost:3000//api/v1/basics/${index}`
fetch(url,{
method: 'DELETE'
}).then((res) => {
res.json()
}).then((res) => {
this.setState({})
})
}
handleSubmit = (character) => {
console.log(character);
const url = "http://localhost:3000//api/v1/basics"
const body = JSON.stringify(
{ name: character.name,
age: character.age,
sex: character.sex,
classs: character.classs,
race: character.race,
height: character.height
})
fetch(url,{
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: body
}).then((res) =>{
return res.json();
}).then((res) => {
this.setState({ addForm: false })
})
}
render() {
const {characters, addForm, editForm, character} = this.state;
let render = ''
if (addForm === true){
render = this.renderAddCharacter(characters)
} else if (editForm === true) {
render = this.renderEditCharacterSKills(character)
} else {
render = this.renderWithOutForms(characters)
}
return render
}
renderAddCharacter(characters){
return(
<div className="characterTable">
<Table
characterData={characters}
removeCharacter={this.removeCharacter}
editCharacter={this.editCharacter}
/>
< SimpleCharacterInfoForm
handleSubmit={this.handleSubmit}
/>
<button onClick={this.addCharacter}>Add Character</button>
</div>
)
}
renderEditCharacterSKills(character){
return(
<div className="characterSkillsForm">
<CharacterSkillsForm
handleEdit={this.handleEdit}
character={character}/>
</div>
)
}
renderWithOutForms(characters){
return(
<div className="characterTable">
<Table
characterData={characters}
removeCharacter = {this.removeCharacter}
editCharacter={this.editCharacter}
/>
<button onClick={this.addCharacter}>Add Character</button>
</div>
)
}
}