javascript – React Router – 历史首先触发而不是等待

嘿伙计们在这里遇到的问题是方法没有以正确的顺序发射.
我无法弄清楚如何制作this.props.history.pushState(null,’/ authors’);在saveAuthor()方法中等待.

将非常感谢帮助.

import React,{ Component } from 'react';
import AuthorForm from './authorForm';
import { History } from 'react-router';

const source = 'http://localhost:3000/authors';


// History Mixin Component Hack
function connectHistory (Component) {
  return React.createClass({
    mixins: [ History ],render () {
      return irstName: '',lastName: '' }
  };

  setAuthorState(event) {
    let field = event.target.name;
    let value = event.target.value;
    this.state.author[field] = value;
    return this.setState({author: this.state.author});
  };

  generateId(author) {
    return `${author.firstName.toLowerCase()}-${author.lastName.toLowerCase()}`
  };

// Main call to the API

  postAuthor() {
    fetch(source,{
        method: 'post',headers: {
        'Accept': 'application/json','Content-Type': 'application/json'
      },body: JSON.stringify({
            id: this.generateId(this.state.author),firstName: this.state.author.firstName,lastName: this.state.author.lastName
        })
    });
  };

  // Calling Save author method but the this.props.history goes first rather than this.postAuthor();

  saveAuthor(event) {
    event.preventDefault();
    this.postAuthor();
    this.props.history.pushState(null,'/authors');
  };

  render() {
    return (
      
最佳答案
Fetch是一个异步函数.在请求完成之前,执行继续到下一行.您需要将代码排队以在请求完成后运行.最好的方法是让你的postAuthor方法返回promise,然后在调用者中使用promise的.then方法.

class ManageAuthorPage extends Component {
// ...
  postAuthor() {
    return fetch(source,lastName: this.state.author.lastName
        })
    });
  };

  saveAuthor(event) {
    event.preventDefault();
    this.postAuthor().then(() => {
      this.props.history.pushState(null,'/authors');
    });
  };
// ...
}

如果您正在使用支持ES7异步函数的转换器,那么您甚至可以在saveAuthor方法中执行此操作,该方法相同且更易于阅读:

  async saveAuthor(event) {
    event.preventDefault();
    await this.postAuthor();
    this.props.history.pushState(null,'/authors');
  };

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...