【发布时间】:2018-01-02 09:05:49
【问题描述】:
在我的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();
}
在我的渲染函数中,我将一些道具值传递给视图文件:
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 值返回一个空数组。
这就是我传递道具的方式:
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。
【问题讨论】:
-
componentWillMount()发生在 之前render()。componentDidMount()发生在之后。 facebook.github.io/react/docs/… -
也。只需将 isFetching 设置为直接道具而不是全局对象。
-
@jered 我已经尝试将
actions.surveyAnswersRequest();放入componentWillMount()并仍然遇到同样的问题 -
render 总是会在您的 ajax 请求返回之前被调用。编写一些代码来处理挂起状态
-
很难说出您的确切问题是什么。能否包含一些带有意外行为的错误或控制台日志?
标签: javascript reactjs