簡體   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