[英]How do i update my state before it renders?
constructor(props) {
super(props);
this.state = {
movie: "Interstellar",
movies: [],
newMovieParsed: {
movieTitle: '',
moviePosters: '',
moviePlot: '',
movieGenre: '',
movieBoxOffice: '',
movieRatings: [],
movieActors: '',
imdbId: '',
}
};
}
onSubmit = movie => {
this.setState(state => ({ ...state, movie }));
this.componentWillMount();
};
componentWillMount() {
this.APIURL = `http://www.omdbapi.com/? s=${this.state.movie}&apikey=${API_KEY}`;
console.log(this.APIURL);
fetch(this.APIURL)
.then(resp => resp.json())
.then(data => {
const movies = data.Search;
this.setState(state => ({
...state, movies
}));
});
}
現在在渲染中
<Search
placeholder="Enter the title of a movie you wish to search and press Enter .."
onSearch={(value) => this.onSubmit(value)}
style={{ width: '100%' }}
/>
一切正常,但是當我放新電影並按Enter時,我必須輸入兩次。 第一個輸入似乎正在更新狀態,然后第二個更新渲染。 我如何更新狀態並使用第一個Enter呈現它? 我也在使用Ant設計。
最主要的是您的setState回調應該是函數的名稱(不帶括號)或調用它的匿名函數:
onSubmit = movie => {
this.setState(state => ({ ...state, movie }));
this.componentWillMount;
};
要么
onSubmit = movie => {
this.setState(state => ({ ...state, movie }));
() => this.componentWillMount();
};
其他提示:通常,您不直接調用生命周期方法(componentWillMount),也不需要在setState中做太多工作。 您可以僅設置要替換的密鑰。
如果您有興趣,下面是一些優化的代碼:
constructor(props) {
super(props);
this.state = {
movie: "Interstellar",
movies: [],
newMovieParsed: {
movieTitle: '',
moviePosters: '',
moviePlot: '',
movieGenre: '',
movieBoxOffice: '',
movieRatings: [],
movieActors: '',
imdbId: '',
}
};
}
onSubmit = movie => {
this.setState({movie}), this.fetchMovie);
};
componentWillMount() {
this.fetchMovie();
}
fetchMovie() {
this.APIURL = `http://www.omdbapi.com/? s=${this.state.movie}&apikey=${API_KEY}`;
console.log(this.APIURL);
fetch(this.APIURL)
.then(resp => resp.json())
.then(data => {
const movies = data.Search;
this.setState(state => ({
...state,
movies
}));
});
}
每次更新狀態時,沒有理由獲得完整的電影列表。 在componentWillMount()中,您可以進行電影的初始獲取,然后在提交時就可以使用新電影來更新狀態。 如果需要,您可以調用React.forceUpdate()來觸發渲染方法。
constructor(props) {
super(props);
this.state = {
movie: "Interstellar",
movies: [],
newMovieParsed: {
movieTitle: '',
moviePosters: '',
moviePlot: '',
movieGenre: '',
movieBoxOffice: '',
movieRatings: [],
movieActors: '',
imdbId: '',
}
};
}
componentWillMount() {
this.getMovies();
});
getMovies = () => {
this.APIURL = `http://www.omdbapi.com/? s=${this.state.movie}&apikey=${API_KEY}`;
console.log(this.APIURL);
fetch(this.APIURL)
.then(resp => resp.json())
.then(data => {
const movies = data.Search;
this.setState(state => ({
...state, movies
}));
}
onSubmit = movie => {
this.setState(state => ({ ...state, movie }));
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.