Xin chào các bạn có vấn đề ở đây với phương pháp kích hoạt không đúng thứ tự. Tôi không thể tìm ra cách làm cho việc chờ đợi this.props.history.pushState(null, '/authors');
trong phương thức saveAuthor().React Router - Lịch sử bắn trước tiên thay vì chờ đợi
Trợ giúp sẽ được đánh giá cao.
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 <Component {...this.props} history={this.history}/>
}
})
}
// Main Component
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', 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 (
<AuthorForm
author={this.state.author}
onChange={this.setAuthorState.bind(this)}
onSave={this.saveAuthor.bind(this)}
/>
);
}
}
export default connectHistory(ManageAuthorPage)
Vâng, loại hình đó ra khỏi bản thân mình nhưng cảm ơn cho phương pháp async ES7. Tôi đọc một số nội dung trên đó và không hiểu nhưng vài dòng mã của bạn đã dạy tôi cách nó hoạt động. Cổ vũ người bạn đời. – Khpalwalk