我正在尝试获取一组电影,并在它获取列表之后更新状态并且列表应该呈现,但问题是渲染方法永远不会从axios回调内部调用,这里是我的代码如下
export default class Movies extends Component {
constructor(props){
super(props);
this.state={movies:[]};
}
componentDidMount(){
axios.get('URL')
.then(response => {
this.setState({movies:response.data});
console.log("Movies",this.state);// I get the values here see screenshot..
});
}
render(){
return(
<div className="row">
<div className="col-md-3">
<MovieList movies={this.state.movies}/>
</div>
<div className="col-md-6">Movie Details</div>
</div>
);
}
}
正如您可以看到上面的代码,在axios回调函数 componentDidMount
中我将响应值设置为状态,但是在执行之后它不会调用渲染,块执行得很好,因为我正确地看到了日志低于
我不明白为什么不叫 render()
?我已经尝试了几种可用的解决方案,但没有一种适用于我,如果我在默认状态下硬编码视频阵列它工作正常,请帮助,如果有人知道解决方案 .
Update(Adding MovieList Code)
class ListItem extends Component {
render(){
return(
<li className="list-group-item">{this.props.moviename}</li>
);
}
}
export default class MoviesList extends Component {
constructor(props) {
super(props);
console.log("Props",props);
this.state={movies:props.movies};
}
renderList(){
const items=this.state.movies.map((movie) => <ListItem moviename={movie.name} key={movie.name}/>);
return items;
}
render(){
return(
<ul className="list-group">
<li className="list-group-item"><h3>Movies</h3></li>
{this.renderList()}
</ul>
);
}
}
谢谢 .
3 回答
您遇到的问题是在ListItem组件中 . 为了使它工作,你需要使用componentWillReceiveProps
在这种情况下,构造被称为 only once 因此,您的组件将不会更新 . 您需要使用函数componentWillReceiveProps,此函数将在每次组件接收新数据时运行 .
例:
你在
MovieList
中添加了componentWillReceiveProps
吗?您应该考虑使您的MoviesList无状态:
通常,您应该尽可能地减少组件的负担 .