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

前端之家收集整理的这篇文章主要介绍了javascript – React Router – 历史首先触发而不是等待前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

将非常感谢帮助.@H_403_3@

@H_403_3@

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 
最佳答案
Fetch是一个异步函数.在请求完成之前,执行继续到下一行.您需要将代码排队以在请求完成后运行.最好的方法是让你的postAuthor方法返回promise,然后在调用者中使用promise的.then方法.@H_403_3@

@H_403_3@

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方法中执行此操作,该方法相同且更易于阅读:@H_403_3@

@H_403_3@

  async saveAuthor(event) {
    event.preventDefault();
    await this.postAuthor();
    this.props.history.pushState(null,'/authors');
  };
原文链接:https://www.f2er.com/js/428973.html

猜你在找的JavaScript相关文章