在我的 componentDidMount()
中,我正在进行 API 调用来获取一些数据,然后此调用设置我在渲染中使用的状态对象。
componentDidMount() {
const { actions } = this.props;
this.increase = this.increase.bind(this);
// api call from the saga
actions.surveyAnswersRequest();
// set breadcrumb
actions.setBreadcrumb([{ title: 'Score' }]);
actions.setTitle('Score');
this.increase();
}
在我的渲染函数中,我将一些 Prop 值传递到 View 文件中:
render() {
const { global, gallery, survey_answers, survey, survey_actual_answers } = this.props;
if (global.isFetching) {
return <Loading />;
}
return this.view({ gallery, survey_answers, survey, survey_actual_answers });
}
我遇到的问题是,第一次加载页面时未设置 survey_actual_answers
属性,但是当我刷新页面时,该属性返回数据正常,其余部分返回脚本将运行。这只是它第一次为该 prop 值返回一个空数组。
这就是我传递 Prop 的方式:
Score.propTypes = {
actions: PropTypes.object.isRequired,
global: PropTypes.object.isRequired,
survey: PropTypes.object.isRequired,
survey_answers: PropTypes.object.isRequired,
gallery: PropTypes.object.isRequired,
survey_actual_answers: PropTypes.array.isRequired,
survey_score_system: PropTypes.array.isRequired,
survey_styles: PropTypes.object.isRequired,
survey_general_doc_data: PropTypes.object.isRequired
};
function mapStateToProps(state, ownProps) {
return {
...ownProps,
global: state.global,
gallery: state.gallery,
survey: state.survey,
survey_actual_answers: state.survey.survey_actual_answers,
survey_answers: state.survey.survey_answers,
survey_score_system: state.survey.survey_score_system,
survey_styles: state.survey.survey_styles,
survey_general_doc_data: state.survey.survey_general_doc_data,
isFetching: state.isFetching
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({
...globalActions,
...galleryActions,
...surveyActions
}, dispatch)
};
}
有谁知道为什么会这样吗?几乎就好像它根本没有调用 componentDidMount。
最佳答案
发生这种情况是因为 React 的基本工作原理。 React 应该给人快速、流畅、敏捷的感觉;应用程序永远不应该被 http 请求或异步代码阻塞。答案是使用生命周期方法来控制 DOM。
组件安装时意味着什么?
更好地理解一些 React 词汇可能会有所帮助。当一个组件被安装时,它被插入到 DOM 中。这是调用构造函数的时候。 componentWillMount 几乎与构造函数同义,并且大约在同一时间被调用。 componentDidMount只会在第一次渲染后调用一次。
componentWillMount --> 渲染 --> componentDidMount
这与重新渲染或更新有何不同?
现在组件位于 DOM 中,您想要更改显示的数据。当调用 setState 或从父组件传递新的 props 时,将会发生组件更新。
componentWillRecieveProps --> shouldComponentUpdate-->componentWillUpdate
-->渲染-->componentDidUpdate
值得注意的是,http 请求通常在 componentDidMount 和 componentDidUpdate 中完成,因为我们可以在这些地方使用 setState 触发重新渲染。
那么如何在渲染发生之前获取数据?
嗯,人们有几种方法可以解决这个问题。第一个是在组件中设置初始状态,以确保即使 http 请求的数据尚未到达,也不会破坏您的应用程序。它将使用默认状态或空状态,直到 http 请求完成。
我通常不喜欢加载模式,但有时这是必要的。例如,当用户登录时,您不希望在他们完成身份验证之前将他们带到站点的 protected 区域。我尝试做的是,当用户登录时使用该加载模式来预先加载尽可能多的数据,而不影响用户体验。
您还可以使组件显示为正在加载,同时不影响网站其余部分的用户体验。我最喜欢的例子之一是 Airbnb website 。请注意,该网站的大部分内容都可以使用,您可以滚动、单击链接,但“体验”下的区域处于加载状态。这是React的正确使用方法,也是setState和HTTP请求在componentDidMount/componentDidUpdate中完成的原因。
关于javascript - React render() 在 componentDidMount() 之前被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45337165/