reactjs - 如何在没有 setState 问题的情况下发出发布请求?
问题描述
我有我想要更新并发送更新发布请求的价值,所以我尝试了这个:
编辑
我添加了更多代表所有组件的代码:
import React from 'react'
import axios from 'axios'
import {Card} from 'react-bootstrap'
class SubmitPage extends React.Component{
constructor(props) {
super(props)
this.state={formname:'',
fields:[''],
values:[''],
submissions:0
}
}
handleChange=this.handleChange.bind(this)
saveChanges=this.saveChanges.bind(this)
componentDidMount=this.componentDidMount.bind(this)
//get the Object from DB and initialize new state
componentDidMount()
{
axios.get('http://localhost:2000/form/'+this.props.match.params.id).then(response =>{
this.setState({
formname:response.data.formname,
fields:response.data.fields,
submissions:response.data.submissions
})
})
.catch(function(error){
})
}
handleChange(e,index)
{
this.setState({
values: {
...this.state.values,
[index.index]: e.target.value
}
});
}
async saveChanges(e)
{
e.preventDefault();
//update the values in field array
const {values}=this.state;
const fields=this.state.fields;
Object.keys(values).map(key =>
fields[key].push(values[key])
)
//get submission and update it
axios.get('http://localhost:2000/form/'+this.props.match.params.id)
.then(response =>{
this.setState({
submissions: response.data.submissions
})
console.log(this.state.submissions)
})
.catch(function(error){
console.log(error);
})
//let submissionsUpdate=this.state.submissions;
// submissionsUpdate=submissionsUpdate+1;
this.setState({
submissions: this.state.submissions+1}, ()=> {
const form={
formname:this.state.formname,
fields:this.state.fields,
submissions: this.state.submissions
}
axios.post('http://localhost:2000/form/update/'+this.props.match.params.id,form) //post after sumbmission value update
.then(res => console.log(res.data));
});
window.location='/'
}
render(){
const {fields}=this.state
return(
<div style={{width:'35%' , margin:"0 auto" ,marginTop:"3%"}}>
<Card >
<Card.Header as="h5">{this.state.formname}</Card.Header>
<Card.Body>
<Card.Text>
<div>{fields.length!==0&&fields.map((fields,index)=> {
return (
<div key={fields[0]}>
<div style={{fontSize:'15px' , marginBottom:"-1px"}}>{fields[0]}</div>
<div><input onChange={(e) => this.handleChange(e, {index})} type={fields[1]}></input></div>
</div>
)
})
}
</div>
<button style={{width:100, marginTop:"10px", marginBottom:"20px"}} type="submit" onClick={this.saveChanges} className="btn btn-dark"> Submit</button>
</Card.Text>
</Card.Body>
</Card>
</div>)
}
}
export default SubmitPage
我的目标是将计数器增加 1 ,但是由于 setState 是异步的,所以出了点问题,结果是或增加了奇怪的数字或没有变化。我做错了什么?
解决方案
推荐阅读
- qt - QtCreator:无法运行编译器“g++”。输出:
- javascript - 在网页运行时如何更改 CodeMirror 设置?
- javascript - 如何用html标签替换字符串
- ios - 如何向 iOS WebApp (PWA) 发送推送通知?
- r - 使用 ggplot2 facet 生成分组相关矩阵热图时无法更改子图背景
- php - 从控制器获取变量以查看
- javascript - Webpack4 如何直接从 HTML 文件加载图像和自定义 javascript?
- javascript - 使用 Discord.js 每 1 分钟发送一次随机消息
- javascript - 从 JSON 字符串动态构建可折叠 UL 的 jQuery 代码
- c# - ListView 的索引在清除它之前是 -1