假设我们有一个有状态的 React 组件(配置为与 Redux 一起使用):
export class SomeComponent extends Component {
state = {
someObject: {}
};
componentWillMount() {
this.props.getNews();
this.props.getFakeNews();
}
render() {
const {
news,
fakeNews
} = this.props;
if(_.isEmpty(news) || _.isEmpty(fakeNews)){
return <div>Loading</div>
}else{
return <div>Here all component stuff</div>
}
}
SomeComponent.propTypes = {
news: PropTypes.array.isRequired,
fakeNews: PropTypes.array.isRequired
};
export const Some = connect(
state => ({
news: newsSelectors.list(state),
fakeNews: fakeNewsSelectors.list(state)
}),
{
getNews,
getFakeNEws
}
)(withStyles(styles)(SomeComponent), withRouter(SomeComponent));
该组件在获取新闻和假新闻时会重新渲染两次。在渲染方法中,我们需要检查它们是否都已加载。
有没有办法只在所有 Prop 加载完毕后才触发渲染?
在完美的场景中,我不希望对 Prop 集进行详细的空/空检查。我相信只要 prop 配置为 required
,React 或 Redux 就应该自行执行此操作。
最佳答案
您可以添加生命周期方法 `shouldComponentUpdate(nextProps, nextState)。
您可以添加以下方法,它应该会为您解决问题:
shouldComponentUpdate(nextProps, nextState) {
if (_.isEmpty(nextProps.news) || _.isEmpty(nextProps.fakeNews)) {
return false;
}
return true;
}
关于javascript - 如何仅在收到 props 时渲染 React(使用 Redux)组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52386457/