繁体   English   中英

页面加载后如何自动运行功能?

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

在我的componentDidMount()中,我在redux文件中调用一个actionCreator进行API调用以获取项目列表。 然后,此项目列表将添加到redux存储中,我可以通过mapStateToProps从我的组件访问该存储。

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

所以在我的render()中,我有:

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

现在,在页面加载时,我需要运行一个需要映射到此list的函数。

假设我有这种方法:

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

但是我在哪里称呼它呢? 我必须在列表已经可用时调用它,因为我的函数会给我一个错误,该列表undefined (如果尚不可用)。

我也不能在render中(在return语句之前)调用它,因为它给我一个错误,那就是render()必须是纯净的。

我可以使用另一种生命周期方法吗?

这是您可以使用Redux收到的道具进行演奏的两种方法

在渲染中进行

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

或者如果您不使用react 16.3或更高版本,请在componentWillReceiveProps方法中执行

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

如果将Api调用放置在componentWillMount或从父级接收道具,则也可以在componentDidMount中执行此操作。

只需执行此操作,并在redux存储中请确保list的初始状态应为[]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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