react根據後臺返回的元件路徑動態的引入元件
搭建react專案時,剛開始路由的配置檔案都是寫死的,每寫一個元件然後都需要自己去路由的配置檔案中進行配置路由。其實剛開始覺得也很正常,因為動態import感覺很難實現。但是專案需求後臺需要記錄那些元件的路徑以及路由 跳轉的路徑。所以就想到了哪些資料都由後臺返回,前端只需要根據後臺返回的路徑動態的引入元件。
一開始後臺返回的是完整路徑,比如說自己寫的元件在pages目錄下,然後在routers目錄中的Index.jsx中引入元件,即‘../pages/header/Header.jsx’,然後後臺就給返回‘../pages/header/Header.jsx’這個路徑,如圖:
實際上是不行的,程式碼如下:
<Switch> {this.state.RouterData && this.state.RouterData.map((item, index) => { return <Route key={index} path={item.path} component={asyncComponent(() => import(item.component))}></Route> })} {/* 重定向 */} <Route path='/' exact render={() => ( <Redirect to="/header" /> )} /> {/* 錯誤路徑跳轉的元件 */} <Route component={ErrorView} /> </Switch>
這樣引入的話會報找不到這個元件,然後就一直想是什麼問題,這樣寫感覺也沒什麼問題,但是確實是報錯找不到這個元件,解決方法就是後臺不能返回這個完整路徑,只能返回這個元件在哪個位置:比如在pages下的header資料夾中的Header.jsx,就只能返回‘pages/header/Header.jsx’,這樣的話我們在引入元件時做一個字串拼接就可以找到這個元件了,程式碼如下:
<Switch> {this.state.RouterData && this.state.RouterData.map((item, index) => { return <Route key={index} path={item.path} component={asyncComponent(() => import('../' +item.component))}></Route> })} {/* 重定向 */} <Route path='/' exact render={() => ( <Redirect to="/header" /> )} /> {/* 錯誤路徑跳轉的元件 */} <Route component={ErrorView} /> </Switch>
注意,this.state.RouterData是後臺返回來的資料然後儲存在state中的,asyncComponent是非同步載入元件的一個方法,程式碼如下:
import React from 'react'; // 這個asyncComponent函式接受一個importComponent的引數,importComponent呼叫時候將動態引入給定的元件。 // 在componentDidMount我們只是簡單地呼叫importComponent函式,並將動態載入的元件儲存在狀態中。 // 最後,如果完成渲染,我們有條件地提供元件。如果不寫null的話,也可提供一個loading,代表著元件正在渲染。 export default function asyncComponent(importComponent) { class AsyncComponent extends React.Component { constructor() { super(); this.state = { component: null } } async componentDidMount() { const { default: component } = await importComponent(); this.setState({component: component}) } render() { const C = this.state.component; return C ? <C {...this.props} /> : null; } } return AsyncComponent; }
這樣就完成了非同步載入元件啦,有什麼還不明白的可以加我QQ: 1274668609