繁体   English   中英

如何通过React-Loadable获取状态? 反应 - 终极版

[英]How to get state via React-Loadable? React-Redux

我编写了一个自定义逻辑来处理react-router-dom .v4中的异步路由加载包。 完美地工作。 但是我也听说过有用的程序包,可以使用不错的API来做到这一点,例如React-Loadable 它有一个问题,我无法从Redux推动的props / state抛出该程序包。

在下面的两个示例中,我的代码从custom样式重写为react-loadable样式。 最后一个是可加载的版本,它不会抛出状态/属性。

我的个人密码:

const asyncComponent = getComponent => {
  return class AsyncComponent extends React.Component {
    static Component = null;

    state = { Component: AsyncComponent.Component };

    componentWillMount() {
      const { Component } = this.state

      if (!Component) {
        getComponent().then(({ default: Component }) => {
          const { store } = this.props // CAN GET THE REDUX STORE

          AsyncComponent.Component = Component;
          this.setState({ Component });
        });
      }
    }

    render() {
      const { Component } = this.state;

      if (Component) {
        return <Component {...this.props} />
      }

      return null;
    }
  };
};

export default withRouter(asyncComponent(() => import(/* webpackChunkName: "chunk_1" */ './containers/Component')))

相同的代码,但带有React-Loadable:

const Loading = () => {
  return <div>Loading...</div>;
}

const asyncComponent = Loadable({
  loader: () => import(/* webpackChunkName: "" */ './containers/Component')
    .then(state => {    
      const { store } = this.props // CANNOT GET THE REDUX STORE!!
    }),
  loading: Loading
})

export default withRouter(asyncComponent)

要通过Provider从Redux存储获取状态,您应该将asyncComponent放在有状态组件包装中,就像在自定义异步逻辑中一样(第一种情况)。

这是因为Loadable库将asyncComponent像函数一样返回给您,而不是构造函数,因此他无法访问当前Redux存储。 因此,工作解决方案将是下一个:

const Loading = () => {
  return <div>Loading...</div>;
}

const asyncComponent = Loadable({
  loader: () => import(/* webpackChunkName: "" */ './containers/Component')
    .then(state => {    
      const { store } = this.props // YOU WILL GET THE REDUX STORE!!
    }),
  loading: Loading
})

class asyncComponentWrapper extends Component{ // Component wrapper for asyncComponent
  render() {
    return <asyncComponent {...this.props} />
  }
}

export default withRouter(asyncComponentWrapper)

PS

我不知道您想做什么,但是如果要在当前存储区中进行reducer注入(可能正是您要执行的操作),则需要通过import而不是从Provider状态显式地包括Redux存储。

暂无
暂无

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

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