首页 > 解决方案 > Reactjs无法将数据传递给父对象

问题描述

我正在尝试将数据从我的数据库传递到我的反应项目中的页面。数据库存储用户数据,并使用 validateCookie() 函数调用数据。我正在从 validateCookie 函数获取数据,但似乎无法将数据从函数中获取到主页,因此我可以使用它来更新用户的状态和日历并将其返回以更新他们在数据库中的信息。

setState 没有向页面状态发送数据。我已经尝试了很多,但我还是新手,所以我有点不合群

import ScheduleSelector from 'react-schedule-selector'
import React, { Component } from 'react';
import Moment from 'moment';
import { Row, Col, Button } from 'react-bootstrap';
import API from '../../utils/API';

class Availability extends Component {
  constructor(props) {
    super(props);
    this.state = {
    user: [],
    email: "",
    calendar: [],
    schedule: [],
  }
  // this.handleInputChange = this.handleInputChange.bind(this);
  // this.handleSubmit = this.handleSubmit.bind(this);
}

  componentDidMount() {
    this.validateCookie();
    console.log(this.state.user); // coming back empty because validate cookie is not passing data upstream
  }


  handleSubmit = (event) => {
    event.preventDefault();
    // let schedule = this.state.schedule;
    // // alert("Your availability has been submitted successfully!");
    // let ISOschedule = this.state.schedule.map(date => Moment(date).toISOString());
    // let newCalendar = this.state.schedule
    console.log(this.state.user);
    API.updateAvailability( 
      this.state.user.email, 
      this.state.user.calendar, 
      this.state.user.schedule)
      .then(r => {
        console.log(r);
    }).catch(e => {
      console.log(e);
    })
  }


  handleChange = newSchedule => {
    this.setState({ schedule: newSchedule.map(date => Moment(date).toISOString()) })
  }

  validateCookie() {
    API.validateCookie()
    .then(res => res.json())
    .then(res => {this.setState({ user: res})})
    .then(res => {
      console.log(this.state) // coming back with loading data aka empty 
      console.log(this.state.user) // coming back with all appropriate data
    })
    .catch(err => console.log(err));
    console.log(this.state.user) // coming back empty
  }

  render() {
    return (
      <div>
        <form ref="form" onSubmit={this.handleSubmit}>
          <ScheduleSelector
            selection={this.state.schedule}
            numDays={7}
            minTime={0}
            maxTime={23}
            onChange={this.handleChange}
          />
          <Row>
            <Col>
              <Button type="submit" className="float-right">Submit Availability</Button>
            </Col>
          </Row>
        </form>
      </div>
    )
  }
}

export default Availability;

标签: javascriptreactjs

解决方案


正如 Swanky 所说,setState() 不会立即更新,您可以监听状态变化并重新渲染 UI。我已经对你的下面做了一些清理setState

validateCookie = () => {
    API.validateCookie()
    .then(res => res.json())
    .then(res => {
        this.setState({...this.state, user: res.user})
        console.log(this.state.user);
    })
    .catch(err => console.log(err));
 }

推荐阅读