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

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

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

将非常感谢帮助.

  1. import React,{ Component } from 'react';
  2. import AuthorForm from './authorForm';
  3. import { History } from 'react-router';
  4. const source = 'http://localhost:3000/authors';
  5. // History Mixin Component Hack
  6. function connectHistory (Component) {
  7. return React.createClass({
  8. mixins: [ History ],render () {
  9. return
最佳答案
Fetch是一个异步函数.在请求完成之前,执行继续到下一行.您需要将代码排队以在请求完成后运行.最好的方法是让你的postAuthor方法返回promise,然后在调用者中使用promise的.then方法.

  1. class ManageAuthorPage extends Component {
  2. // ...
  3. postAuthor() {
  4. return fetch(source,lastName: this.state.author.lastName
  5. })
  6. });
  7. };
  8. saveAuthor(event) {
  9. event.preventDefault();
  10. this.postAuthor().then(() => {
  11. this.props.history.pushState(null,'/authors');
  12. });
  13. };
  14. // ...
  15. }

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

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

猜你在找的JavaScript相关文章