简体   繁体   中英

How to automatically run a function after a page loads in react?

In my componentDidMount(), I am calling an actionCreator in my redux file to do an API call to get a list of items. This list of items is then added into the redux store which I can access from my component via mapStateToProps .

const mapStateToProps = state => {
    return {
        list: state.list
    };
};

So in my render(), I have:

render() {
    const { list } = this.props;
}

Now, when the page loads, I need to run a function that needs to map over this list .

Let's say I have this method:

someFunction(list) {
    // A function that makes use of list
}

But where do I call it? I must call it when the list is already available to me as my function will give me an error the list is undefined (if it's not yet available).

I also cannot invoke it in render (before the return statement) as it gives me an error that render() must be pure.

Is there another lifecycle method that I can use?

These are two ways you can play with received props from Redux

Do it in render

  render() {
       const { list } = this.props;
       const items = list && list.map((item, index) => {
             return <li key={item.id}>{item.value}</li>
       });
       return(
            <div>
                 {items}
           </div>
       );
    }

Or Do it in componentWillReceiveProps method if you are not using react 16.3 or greater

 this.state = {
      items: []
}
 componentWillReceiveProps(nextProps){
       if(nextProps.list != this.props.list){
            const items = nextProps.list &&    nextProps.list.map((item, index) => {
                  return <li key={item.id}>{item.value}</li>
             });
             this.setState({items: items});
        }
    }

    render() {
        const {items} = this.state;
        return(
           <div>
               {items}
           </div>
        );
     }

You can also do it in componentDidMount if your Api call is placed in componentWillMount or receiving props from parent.

Just do this, and in redux store please make sure that initial state of list should be []

const mapStateToProps = state => {
    return {
        list: someFunction(state.list)
    };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM