在使用react-router更改路由之前获取数据

时间:2016-12-31 02:51:23

标签: reactjs redux react-router laravel-5.3

我在后端使用反应 react-router redux laravel 我使用了所有最新版本,我实际上对这些版本很新,我只是决定将我的开发经验提升到一个新的水平,并决定根据我喜欢它们的方式使用这些,很多

我遇到以下问题:当我处于 about-us 路线时,我点击主页,但在路由器呈现主页之前,它需要对服务器进行异步调用。我注意到我理论上需要它是异步的,因为它需要在继续下一个路由之前完成。

然后,我想在页面顶部有一个栏,指示我在服务器上获取依赖项。一旦完成,它应该进入归属路线

一个实际的例子是GitHub,例如你在代码选项卡,然后你点击问题标签,蓝色加载栏将出现在最顶层指示正在获取数据或依赖项的页面,然后一旦完成,它将呈现下一个路由。我该怎么做?

我认为我应该使用某种中间件,所以在路由更改之前我应该​​发送一个动作来获取我需要的依赖项,然后一旦完成,我应该发出一个动作将更新redux商店的某些部分,我无法找到一种方法来应用中间件做出反应路由器,但我真的不知道在哪里以及如何开始。

3 个答案:

答案 0 :(得分:3)

以下是没有redux的示例:

<强> MyPage.jsx

import React from 'react'
import { fetchDataForMyPage } from './someApi'

let data = {}

export default class MyPage extends React.Component {
    constructor() {
        super()
        this.state = {
            /* ... */
            data: data
            /* ... */
        }
    }
    render() {
        /* ... */
    }
    static loadData(routerParams, callback) {
        fetchDataForMyPage(routerParams).then((fetchedData) => {
            data = fetchedData
            callback()
        })
    }
    componentWillReceiveProps() {
        this.setState({
            data: data
        })
    }
}

<强> Routes.jsx

import React from 'react'
import { Route } from 'react-router'
import App from './components/App'
import MyPage from './components/MyPage'

const loadDataOnEnter = (nextState, replace, callback) => {
    const nRoutes = nextState.routes.length
    const component = nextState.routes[nRoutes-1].component
    const params = nextState.params
    component.loadData(params, () => callback())
}

module.exports =
    <Route path="/" component={App}>
        <Route path="mypage/:param1" component={MyPage} onEnter={loadDataOnEnter} />,
        <Route path="anotherpage" component={AnotherPage} onEnter={loadDataOnEnter} />,
        <Route path="somepath" component={SomePageWithoutDataPreloading} />
    </Route>

答案 1 :(得分:0)

在进行服务器调用的HomePage组件中可以更好地处理。您需要设置一个指示正在处理呼叫的状态,例如this.state.loadingthis.state.processing,然后您可以根据这些值显示/隐藏加载程序或栏。 E.g

export default class Home extends React.Component {
 constructor(props) {
  super(props)
   this.state = {processing: false}
 }
 getData(){ //method that makes the server call
  ...//make the call to the server
  this.setState({processing: true})
  //check that the server call returns something and transition to next page when data is returned
 }

 render() {
  return (
   <div>
    {this.state.processing ? "return the loader image" : "else maybe return null"}
    <div>content of the home page</div>
   </div>
  )
 }
}

答案 2 :(得分:-1)

如果您使用普通的redux和路由器,您可以使用路由器的生命周期功能,例如 onEnter (在进入视图之前调用)或 onLeave ...,那么你可以做任何你喜欢的事情,当你调用它时,它们会接受回调函数,实际的路由就会发生。

另一个选择是使用一些redux promise中间件用于异步作业,例如 redux-promise-middleware ,或者只使用 thunk loadingbar (因为我们在生产中使用它们,这与异步操作完美配合。

Redux Promise Middleware

React Redux Loading Bar