javascript - 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;
解决方案
正如 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));
}
推荐阅读
- flutter - 使用 valuelistenablebuilder 平滑动画过渡
- angular - primeng p-editor 无法更新 html
- mysql - MySQL:条件触发器
- airflow - 如何显示从 Apache Airflow 到自定义 webapp 的 DAG 进度
- ssl - 禁用 tls 1.0/1.1 和 ssl2.0/3.0 后网站关闭
- java - 需要专门获取 java-1.8.0-openjdk-amd64 并安装?
- python-3.x - Django:如何在管理视图中为 readonly_field 设置默认随机值?
- tensorflow - TensorFlow.js 预测 2D 数据(单值)
- computer-vision - 2个视图的捆绑调整有意义吗?
- excel - 将具有相似名称后缀的工作表分组