React async await跳过第一个响应

时间:2019-04-07 13:24:08

标签: reactjs async-await

我有一个带有两个辅助方法的组件,这些方法调用动作创建者。 我希望辅助方法可以与数据库交互,而不是呈现从数据库中获取所有数据的方法

这是辅助方法:

 handleDeleteCourse = async course => {
    await this.props.deleteCourse(course && course.id);
    this.props.fetchCourses();
  };

  handleCreateCourse = async (state) => {
    await this.props.addCourse(state);
    this.props.fetchCourses();
  };

handleDeleteCourse很好用, 我有一个带有onClick的删除按钮,该按钮调用delete helper方法,该行从数据库中删除,并且调用this.props.fetchCourses();操作从数据库中删除所有行(下面是fetchCourses代码)。

问题出在handleCreateCourse上,当我单击所需按钮时,数据进入了数据库,但是我没有在屏幕上看到新行。当我发送新行时,我会在屏幕上看到上次发送的数据。

是什么原因引起的?我添加了addCourse动作创建者

    import React, { Component } from "react";
import { connect } from "react-redux";
import {
  Container,
  Form,
  Button,
  Col,
  Row,
  Table,
  striped,
  bordered,
  hover
} from "react-bootstrap";

import { fetchCourses, deleteCourse, addCourse } from "../../actions";

class Courses extends Component {
  state = {
    id: Math.random(),
    courseName: "",
    courseWeeklyHours: "",
    courseType: false
  };

  componentDidMount() {
    this.props.fetchCourses();
  }

  handleDeleteCourse = async course => {
    await this.props.deleteCourse(course && course.id);
    this.props.fetchCourses();
  };

  handleCreateCourse = async (state, e) => {
    await this.props.addCourse(state);
    this.props.fetchCourses();
  };

  onChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  render() {
    const prevProps = prevProps => {
      console.log("this.props", this.props.courses.length);
      console.log("prevProps ", prevProps.courses.length);
    };

    const courses = this.props.courses.map(course => {
      return (
        <tr key={course && course.id}>
          <td>
            {course.coursename}- {course && course.id}
          </td>

          <td>{course.coursetype ? "yes" : "no"}</td>

          <td>{course.courseweeklyhours}</td>

          <td>
            <button onClick={() => this.handleDeleteCourse(course)}>הסר</button>
          </td>
        </tr>
      );
    });

    return (
      <Container>
        <Table striped bordered hover className="text-right">
          <thead>
            <tr>
              <th>שם הקורס</th>
              <th>סוג הקורס</th>
              <th>שעות שבועיות</th>
              <th />
            </tr>
          </thead>
          <tbody>{courses}</tbody>
        </Table>

        {/* <Form onSubmit={this.onSubmit}> */}
        <Form>
          <Row>
            <Col>
              <Form.Group controlId="courseForm.ControlSelect1">
                <Form.Control
                  type="text"
                  name="courseName"
                  defaultValue={this.state.courseName}
                  onChange={this.onChange.bind(this)}
                />
              </Form.Group>
            </Col>
            <Col>
              <Form.Group controlId="formGridState">
                <Form.Control
                  as="select"
                  name="courseType"
                  defaultValue={this.state.courseType}
                  onChange={this.onChange.bind(this)}
                >
                  <option id="typeselect" value="">
                    Select...
                  </option>
                  <option value="1">אקדמי</option>
                  <option value="0">מכינה</option>
                </Form.Control>
                {this.state.courseTypeError}
              </Form.Group>
            </Col>
            <Col>
              <Form.Group>
                <Form.Control
                  type="number"
                  placeholder="Course grade"
                  name="courseWeeklyHours"
                  id="courseWeeklyHours"
                  defaultValue={this.state.courseWeeklyHours}
                  onChange={this.onChange.bind(this)}
                />
                {this.state.courseGradeError}
              </Form.Group>
            </Col>

            <Col>
              <Form.Group controlId="submit">
                {/* <Button variant="primary" type="submit" onClick={() => this.handleCreateCourse(this.state)}>
            submit
          </Button> */}
                <Button
                  variant="primary"
                  onClick={() => this.handleCreateCourse(this.state)}
                >
                  שלח
                </Button>
              </Form.Group>
            </Col>
          </Row>
        </Form>
      </Container>
    );
  }
}

const mapStateToProps = state => {
  console.log("state ", state);

  return {
    courses: state.courses
  };
};

export default connect(
  mapStateToProps,
  { fetchCourses, deleteCourse, addCourse }
)(Courses);

fetchCourses动作:

export const fetchCourses = () => {
    return async (dispatch) => {
        const response = await mysql.get('courses/Courses.php');

        dispatch({
            type: FETCH_COURSES,
            payload: response
        })

    }

}

mysql var:

import axios from 'axios';

export default axios.create({
    baseURL: 'http://127.0.0.1/react/calc/api/'
});

addCourse动作创建者:

export const addCourse = (data) => {

    return (dispatch) => {
        fetch("http://127.0.0.1/react/calc/api/courses/Courses.php", {
                method: "POST",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(json => {
                dispatch({
                    type: ADD_COURSE,
                    value: json
                });
                console.log('json ', json);
            })
            .catch(error =>
                console.log('parsing faild', error)
            )
    };
};

0 个答案:

没有答案