我有想要更新并发送更新后请求的值,所以我尝试了此操作:
编辑
我添加了更多代表所有组件的代码:
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是asych,所以出了点问题,结果是或增加了奇数或没有变化。 我在做什么错了?