簡體   English   中英

在解析路由之前獲取數據

[英]Fetch data before resolve route

我正在使用路由“react-router”庫。 在渲染頁面組件之前,我需要獲取數據。 我想在每次路由之前顯示加載器,因為所有路由都需要來自服務器的數據。 我所有的組件都由 controller 驅動,所以我的解決方案是在所有組件的構造函數中創建這個 controller,然后創建 controller 獲取數據。

它可以工作,但我正在使用 typescript 並且我希望在沒有(。)檢查數據的情況下訪問數據。 對於使用等待數據並呈現當前頁面的包裝器組件的更好解決方案,對於第一次路由它可以工作,但 componentDidMounnt “代碼下方”僅被調用一次。 所以第二次循環不起作用。

<Router>
   <Switch>
     <MyRoute path="/login" component={LoginPage} exact={true} />
     <MyRoute path="/reg" component={RegistrationPage} exact={true} />
   </Switch>
</Router>
/*MyRoute*/
async componentDidMount() {
    try {
            await this.props.routeController.getController(this.props.path).then((controller: PageController) => {
                this.setState({
                    controller: controller
                })
                this.props.routeController.loading = false;
            })
        } catch(err) {
            // error handling
        }
    }

    render() {
        if (!this.props.routeController.loading) {
            const { controller } = this.state; 
            return (
                <this.props.component controller={controller} />
            )
        }

        return <div>LOADING</div>;
    }

所以我需要在路由之前獲取數據。 之后,我需要使用道具中的數據渲染頁面組件。 有可能還是這個問題的好解決方案? 如果沒有,我該如何解決異步路由的問題。 謝謝:-)

使 state isLoading: false,然后在 componentWiilMount() / DidMount() 中設置 isLoading state 為 true。 在獲取成功后將 isLoading 重置為 false;

componenetWillMount/didMount(){
this.setState({
isLoading: true
})
fetchData().then(res => this.setState(isLoading: false))
.catch(err => this.setState({isLoading: false}));


render(){
return(
{this.state.isLoading ? <Loader /> : <Component View /> }
)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM