首页 > 解决方案 > 捕获新状态变量以发送到服务器的最佳方法

问题描述

我正在尝试在 React 类组件中使用一种方法,将用户数据从我的前端发送到我的后端。现在,如果我对它进行硬编码,我可以让它通过。但是我很难传递这些值,因为它们会改变,就像它们的状态一样。初始状态设置为 0,然后用户将输入一个数字,状态将发生变化,但我无法将更改后的状态传递到我的数据库/后端。下面是我的代码。

前端:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hits: [],
      desc: [],
      outdoor: 0,
      water: 0,
      value: null,
      outBeforeCalc: [],
      waterBeforeCalc: [],
      waterPercentage: 0,
      outdoorPercentage: 0,
      userId: null
    };
  }

  componentDidMount() {
    this.fetchData();
    this.addHealthData();
  }
...
addHealthData = () => {
    let addHealthDataUrl = "http://localhost:10240/weather/save"

    let queryParams = {
      'userId': this.state.userId,
      'sun': this.state.outdoor,
      'water': this.state.water,
      'progress': this.state.value
    }
    fetch(addHealthDataUrl, {
      method: 'post',
      body: JSON.stringify(queryParams),
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(response => response.json())
      .then(data => {
        if (data.code == "200") {
          this.props.sendMessage("Your data has been saved!")
        } else {
          this.props.sendMessage(`We've encountered a problem.`);
        }
      })
      .catch((error) => {
        console.error('Error:', error);
      })
  }

后端:

app.post('/weather/save', (req, res) => {
    try {
        let userId = req.body.userId;
        let sun = req.body.sun;
        let water = req.body.water;
        let progress = req.body.progress;
        console.log(req.body)

        db.run(queries.Save(userId, sun, water, progress),
            (message) => {

                res.write(`Weather information saved successfully.`);
                console.log(`Weather information saved successfully.`);
                res.end();
                return;
            },
            (error) => {
                res.write(`Error saving weather information`);
                console.log('Error saving weather information. ', error);
                res.end();
                return;
            });
    } catch (er) {
        res.send('Error: ' + er)
    }
});

我需要以某种方式从服务器获取我的 userId。后端:

app.post('/account/login', (req, res) => {
    try {
        let email = req.body.email;
        let password = req.body.password;

        db.run(queries.Login(email, password),
            (message) => {
                let id = '';
                if (message.length > 0)
                    id = message[0].ID;

                if (id > 0) {
                    res.write(`Login was successful, UserId: ${id}`);
                    console.log(`Login was successful, UserId: ${id}`);
                }
                else {
                    res.write(`Login ecnountered error! Please specify valid EMAIL and PASSWORD`);
                    console.log('Login ecnountered error! Please specify valid EMAIL and PASSWORD. ');
                }

                res.end();
                return;
            },
            (error) => {
                res.write(`Login ecnountered an error! Please specify valid EMAIL and PASSWORD`);
                console.log('Login ecnountered an error! Please specify valid EMAIL and PASSWORD. ', error);
                res.end();
                return;
            });

    } catch (er) {
        res.send('Error: ' + er)
    }

});

前端:

getUserId =() => {
    let getUserIdUrl = `http://localhost:10240/weather/fetch?user=${this.state.userId}`

    let queryParams = {
      "userId": this.state.userId
    }

    fetch(getUserIdUrl, {
      method: 'get',
      body: JSON.stringify(queryParams),
      headers: {
        "Content-Type": "application/json"
      }
    })
    .then(response => response.json())
          .then(data => {
            if (data.code == "200") {
                if (data.userId) {
                this.setState({
                    userId: data.userId
                })
              }
            } else {
              console.log(`We've encountered a problem`);
            }
          })
          .catch((error) => {
            console.error('Error:', error);
          })
      

  }

用户更新状态的代码:

onChangeOutdoor = e => {
    this.setState({
      outdoor: +e.target.value
    })
  }

  onChangeWater = e => {
    this.setState({
      water: +e.target.value
    })
  }

  Formula(e) {
    e.preventDefault();
    let joinedOut = this.state.outBeforeCalc.concat(this.state.outdoor);
    this.setState({ outBeforeCalc: joinedOut });

    let joinedWater = this.state.waterBeforeCalc.concat(this.state.water);
    this.setState({ waterBeforeCalc: joinedWater });

    let OutdoorCo;
    let WaterCo;
    this.setState({}, () => {
      let outSum = this.state.outBeforeCalc.reduce((a, b) => a + b, 0);
      OutdoorCo = (outSum * 100) / 15;
      let waterSum = this.state.waterBeforeCalc.reduce((a, b) => a + b, 0);
      WaterCo = (waterSum * 100) / 80;
      const sum = (WaterCo + OutdoorCo) / 2;
      this.setState({
        value: +sum,
        waterPercentage: WaterCo,
        outdoorPercentage: OutdoorCo
      });
      this.setState({
        // hits: [],
        // desc: [],
        outdoor: 0,
        water: 0
      });
    });
  }
...
 <form onSubmit={e => this.Formula(e) && this.addHealthData }>
        <div>
          <div className="field1">
            <TextField
              id="standard-number1"
              label="Outdoor Time"
              type="number"
              value={`${this.state.outdoor}`}
              onChange={this.onChangeOutdoor}
              InputLabelProps={{
                shrink: true,
              }}
            />
            outdoor percentage : {this.state.outdoorPercentage}
            </div>
          

          <div className="field2" noValidate autoComplete="off">
            <TextField
              id="standard-number2"
              label="Water Consumption"
              type="number"
              value={`${this.state.water}`}
              onChange={this.onChangeWater}
              InputLabelProps={{
                shrink: true,
              }}
            />
            water percentage : {this.state.waterPercentage}
          </div>
        </div>
        <Button variant="contained" color="secondary" style={{ marginTop: 25, marginLeft: '44%' }} type="submit" onKeyDown={keyPress}>
            {" "}
             Get Energy Level{" "}
          </Button>
          </form>
          <div className="progress-div">
          <LinearProgress
          classes={{barColorPrimary: classes.barColorPrimary}}
            variant="determinate"
            style={{ margin: 20, width: 400, marginLeft: '36%', height: 50 }}
            value={this.state.value <= 100 ? this.state.value : 100}
          />
          <h4 style={{marginLeft:"45%"}}>
            {typeof this.state.value === "number"
              ? `${this.state.value}%`
              : this.state.value}
          </h4>
        </div>
        {/* <ProgressBar width={400} percent={this.state.percent} /> */}
      </div>

谢谢!

标签: javascriptmysqlreactjsexpressbackend

解决方案


推荐阅读