嘿伙计们在这里遇到的问题是方法没有以正确的顺序发射.
我无法弄清楚如何制作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');
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。