반응형
라우터 반응 - 대기하는 대신 히스토리가 먼저 발생
나는 여기에 올바른 순서가 아닌 방법으로 발사하는 방법이 문제가 있다.어떻게 만들는지 알 수가 없다.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 <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)
Fetch는 비동기 함수다.요청이 완료되기 전에 다음 줄까지 실행한다.요청이 완료된 후 실행하려면 코드를 대기열에 넣어야 한다.그렇게 하는 가장 좋은 방법은 당신의 자리를 만드는 것이다.작성자 방법은 약속을 반환한 후, 발신자에게 약속의 .den 방법을 사용한다.
class ManageAuthorPage extends Component {
// ...
postAuthor() {
return 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
})
});
};
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');
};
그래서 이것은 당신의 게시물이작성자 메서드에 비동기 호출이 있음fetch()
내면의함수의 콜백으로 함수를 전달하고, 그 함수의 "완료" 콜백 안에서 그 함수를 호출하고자 하는 시간이다.fetch
그 암호는 이렇게 생겼을 거야
postAuthor(callback) {
fetch(source, {
/* Methods, headers, etc. */
}, () => {
/* Invoking the callback function that you passed */
callback();
});
);
saveAuthor(event) {
event.preventDefault();
/* Pass in a function to be invoked from within postAuthor when it is complete */
this.postAuthor(() => {
this.props.history.pushState(null, '/authors');
});
};
참조URL: https://stackoverflow.com/questions/35305228/react-router-history-fires-first-rather-waiting
반응형
'IT이야기' 카테고리의 다른 글
어떻게 하면 이것에 대한 반응을 얻을 수 있을까.vue.js 2에 $store.properties? (0) | 2022.03.26 |
---|---|
외부 요소 클릭 감지 (0) | 2022.03.26 |
Python 3으로 pip을 설치하는 방법? (0) | 2022.03.26 |
Vuetify v-btn 및 Vue 라우터를 사용하여 새 창에서 링크 열기 (0) | 2022.03.26 |
useLimenscer([state,dispatch]]) 및 useContext를 사용하여 불필요한 리렌더를 피하는 방법 (0) | 2022.03.26 |