我如此努力地阅读和尝试,但仍然找不到成功将 componentWillReceiveProps 替换为 getDerivedStateFromProps 的方法。这是我的代码,componentWillReceiveProps 一个工作正常。但是我尝试的 getDerivedStateFromProps 不起作用(在 componentDidMount() 运行正常后,state.movies 最终变为 [] 为空)。感谢您的帮助!
class OK_MovieListContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: [],
title:''
};
this.discoverMovieDB = this.discoverMovieDB.bind(this);
this.searchMovieDBAPI = this.searchMovieDBAPI.bind(this);
}
componentDidMount() {
this.discoverMovieDB();
}
UNSAFE_componentWillReceiveProps(nextProps, prevState) {
if (nextProps.match.params.title && prevState.title !== nextProps.match.params.title) {
this.searchMovieDBAPI(nextProps.match.params.title);
this.setState({ title: nextProps.match.params.title });
}
}
async discoverMovieDB() {
.....
}
async searchMovieDBAPI(title) {
const promisedData = await MovieDBAPI.search(title);
if (promisedData) {
this.setState({ movies: promisedData[0] });
}
}
}
render() {
return (
<div className="App">
<MovieList movies={this.state.movies} />
</div>
);
}
}
export default OK_MovieListContainer;
以下是我尝试使用 getDerivedStateFromProps 的方法,但无法正常工作(在 componentDidMount() 运行正常后, state.movies 最终变为 [] 为空)。....TT
class MovieListContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: [],
title:''
};
this.discoverMovieDB = this.discoverMovieDB.bind(this);
this.searchMovieDBAPI = this.searchMovieDBAPI.bind(this);
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.match.params.title && nextProps.match.params.title !== prevState.title) {
return {
//this state changes then componentDidUpdate is called
title: nextProps.match.params.title
};
}
//indicate state update not required
return null;
}
componentDidMount() {
this.discoverMovieDB();
}
componentDidUpdate(nextProps, prevState) {
if (nextProps.match.params.title !== prevState.title) {
this.searchMovieDBAPI(nextProps.match.params.title);
this.setState({ title: nextProps.match.params.title });
}
}
async discoverMovieDB() {
.....
}
async searchMovieDBAPI(title) {
const promisedData = await MovieDBAPI.search(title);
if (promisedData) {
this.setState({ movies: promisedData[0] });
}
}
}
render() {
return (
<div className="App">
<MovieList movies={this.state.movies} />
</div>
);
}
}
export default MovieListContainer;
太感谢了!