在componentDidMount()

时间:2017-07-26 20:50:13

标签: javascript reactjs

在我的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,但是当我刷新页面时,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。

3 个答案:

答案 0 :(得分:29)

这是因为React如何从根本上发挥作用。 React应该感觉快速,流畅和活泼;应用程序永远不会被http请求或异步代码堵塞。答案是使用生命周期方法来控制DOM。

组件安装时意味着什么?

更好地理解一些React词汇表可能会有所帮助。安装组件时,它将被插入DOM。这是在调用构造函数时。 componentWillMount几乎与构造函数同义,并且大约在同一时间调用。 componentDidMount仅在第一次渲染后调用一次。

componentWillMount - &gt; 渲染 - &gt; componentDidMount

与重新渲染或更新有什么不同?

现在该组件位于DOM中,您希望更改显示的数据。当调用setState或从父组件传递新的props时,将发生组件更新。

componentWillRecieveProps - &gt; shouldComponentUpdate - &GT; componentWillUpdate
  - &GT; 呈现 - &GT; componentDidUpdate

还可以注意到http请求通常在componentDidMount和componentDidUpdate中完成,因为这些是我们可以使用setState触发重新渲染的地方。

那么如何在渲染发生之前获取数据?

嗯,人们有几种方法可以解决这个问题。第一个是在组件中设置初始状态,以确保如果来自http请求的数据尚未到达,它将不会破坏您的应用程序。它将使用默认或空状态,直到http请求完成。

我通常不喜欢装载模式,但有时候是必要的。例如,当用户登录时,您不想将他们带到您网站的受保护区域,直到他们完成身份验证。我尝试做的是在用户登录到尽可能多的数据时使用该加载模式,而不会影响用户体验。

您还可以将组件显示为加载,同时不影响网站其余部分的用户体验。我最喜欢的一个例子是Airbnb website。请注意,可以使用该网站的大部分内容,您可以滚动,点击链接,但“&#39;体验”下的区域可以使用。处于加载状态。这是使用React的正确方法,也是在componentDidMount / componentDidUpdate中完成setState和HTTP请求的原因。

答案 1 :(得分:2)

在componentdidmount中使用setState。这是我的代码:

 async componentDidMount() {

    danhSachMon = await this.getDanhSachMon();
    danhSachMon=JSON.parse(danhSachMon);
    this.setState(danhSachMon);
}

render() {
    return (
        <View>
            <FlatList
                data={danhSachMon}
                showsVerticalScrollIndicator={false}
                renderItem={({ item }) =>
                    <View >
                        <Text>{item.title}</Text>
                    </View>
                }
                keyExtractor={(item, index) => index.toString()}
            />
        </View>
    )
}

答案 2 :(得分:1)

componentWillMount已弃用。现在,您需要使用“ DidMount”,并在完成渲染并更改渲染上的DOM后,react将处​​理其他所有内容。

确保在渲染中更新并使用正确的变量/状态/属性。

componentDidMount() {    
    const { applicationId } = this.props;
    if (applicationId) {
      ApplicationService.getQuotesByApplicationId(applicationId).then((response) => {
        const quotes = _.get(response, 'data.data');
        this.setState({
          quotes,
        });
      });

    ....

    }

    render() {

        const quotes = _.get(this.state, 'quotes', null);
        return (
          <div className="application">
            <h4 className="application__sub">Application</h4>
            <h1 className="application__title">Quote Comparison</h1>
            <div className="form-wrapper">
              {this.renderQuotes(quotes)}
            </div>
            <div />
          </div>
        );
      }

在这里,我从API获取引号,并在完成后立即将其设置为状态变量,然后渲染和反应完成其工作。

相关问题