首页 > 解决方案 > 使用 axios 响应发布请求无法正常工作

问题描述

我的数据很少,现在我想在反应中使用 axios post 将其保存在数据库中。

我有两个字段,但在两个字段中都有相同的数据,不知道这里出了什么问题。

我的代码:

 state = {
        salonName: '',
        locationCity: '',
  };
  handleChange = event => {
        this.setState({ salonName: event.target.value });
        this.setState({ locationCity: event.target.value });
};
 handleSubmit = event => {
        event.preventDefault();
        const salonData = {
            salonName: this.state.salonName,
            locationCity: this.state.locationCity,
 };
 axios({
                method: "post",
                url: "http://localhost:4200/addsalon",
                headers: {},
                data: {
                    salonName: salonData.salonName,
                    locationCity: salonData.locationCity,
  },
                });
                }
render() {
        return (
<div>
<input type="text" className="form-control" placeholder="Enter Salon Name..." name="salonName" onChange={this.handleChange} />
<input type="text" className="form-control" placeholder="Enter City" name="locationCity"  onChange={this.handleChange} />
</div>

但我在数据库中得到相同的值,如下所示:- {"_id":"60ac7dd4ccfa1c07a8df84d8","salonName":"Delhi","locationCity":"Delhi","__v":0}]

感谢你付出的努力!

标签: javascriptreactjs

解决方案


手柄变化的问题。如果有人更改,您将同时更新两者

 handleChange = event => {
        if(event.target.name ===='salonName'){
        this.setState({ salonName: event.target.value });
        }else if(event.target.name ===='locationCity'){
        this.setState({ locationCity: event.target.value });
        }
};


推荐阅读