componentWillUnmount() not being called when refreshing the current page

前端 未结 3 1569
Happy的楠姐
Happy的楠姐 2020-12-13 13:04

I\'ve been having this problem where my code in the componentDidMount() method wasn\'t firing properly when refreshing the current page (and subsequently, the c

3条回答
  •  生来不讨喜
    2020-12-13 13:17

    I see that this question has over a thousand views, so I'll explain how I solved this problem:

    To solve this particular problem, the most sensible way is to create an upper level component that loads your subscription or database, so that you load the required data before passing it to your child component, which would completely remove the need to use componentWillMount(). Also, you can do the computations in the upper level component and just pass them down as props to use in your receiving component

    For example:

    class UpperLevelComponent extends React.Component {
    
    render() {
    if(this.props.isReady) {
    return()
    }
    }
    }
    
    export default createContainer(() => {
    const data = Meteor.subscribe("myData");
    const isReady = data.ready();
    
    return {
    isReady,
    data: MyData.find.fetch()
    }
    })
    

    In the example above, I use Meteor's reactive container to get my MongoDB data and wait for it to completely finish subscribing before I render the child component, passing it any props I want. If you load all your data in the higher level component, you won't have to rely on the componentWillMount() method to trigger after every refresh. The data will be ready in the upper level component, so you can use it however you want in the child component.

提交回复
热议问题