React render() is being called before componentDidMount()

后端 未结 3 1707
面向向阳花
面向向阳花 2020-12-03 01:14

In my componentDidMount() I am making an API call to fetch some data, this call then sets a state object that I use in my render.

componentDidMo         


        
相关标签:
3条回答
  • 2020-12-03 01:33

    This is happening because of how React works fundamentally. React is supposed to feel fast, fluent and snappy; the application should never get clogged up with http requests or asynchronous code. The answer is to use the lifecycle methods to control the DOM.

    What does it mean when a component mounts?

    It might be helpful to understand some of the React vocabularies a little better. When a component is mounted it is being inserted into the DOM. This is when a constructor is called. componentWillMount is pretty much synonymous with a constructor and is invoked around the same time. componentDidMount will only be called once after the first render.

    componentWillMount --> render --> componentDidMount

    How is that different than rerendering or updating?

    Now that the component is in the DOM, you want to change the data that is displayed. When calling setState or passing down new props from the parent component a component update will occur.

    componentWillRecieveProps --> shouldComponentUpdate-->componentWillUpdate
    -->render-->componentDidUpdate

    It is also good to note that http requests are usually done in componentDidMount and componentDidUpdate since these are places that we can trigger a rerender with setState.

    So how do I get the data before the render occurs?

    Well, there are a couple of ways that people take care of this. The first one would be to set an initial state in your component that will ensure that if the data from the http request has not arrived yet, it will not break your application. It will use a default or empty state until the http request has finished.

    I usually don't like to have a loading modal, but sometimes it is necessary. For instance, when a user logs in you don't want to take them to a protected area of your site until they are finished authenticating. What I try to do is use that loading modal when a user logs in to front load as much data as I possibly can without affecting the user experience.

    You can also make a component appear as loading while not affecting the user experience on the rest of the site. One of my favorite examples is the Airbnb website. Notice that the majority of the site can be used, you can scroll, click links, but the area under 'experiences' is in a loading state. This is the correct way to use React and is the reason why setState and HTTP requests are done in componentDidMount/componentDidUpdate.

    0 讨论(0)
  • 2020-12-03 01:36

    componentWillMount is deprecated. Now you need to use "DidMount" and as soon as it finishes and changes the DOM on render, react will handle everything else.

    Make sure you update and use the correct variables/state/props in the render.

    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>
            );
          }
    

    Here I get the quotes from the API and as soon as it finishes it set a variable in the state, then the render and react do their work.

    0 讨论(0)
  • 2020-12-03 01:48

    Using setState in componentdidmount. This my code:

     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>
        )
    }
    
    0 讨论(0)
提交回复
热议问题