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

IT技术 reactjs redux react-router laravel-5.3
2021-05-17 12:32:02

在后端使用reactreact-routerreduxlaravel,我使用的是所有最新版本,实际上我对这些版本很陌生,我只是决定我应该将我的开发经验提升到一个新的水平和决定根据我喜欢它们的方式使用这些,很多

我有以下问题:当我在对美的路线,然后我点击主页,但路由器呈现前主页,它需要做出一个异步调用服务器。我注意到理论上我需要这是异步的,因为它需要在继续下一条路线之前完成。

然后,我希望在页面顶部有一个栏,指示我正在获取服务器上的依赖项。完成后,它应该继续回家路线

一个实际的例子是 GitHub,例如你在代码选项卡上,然后单击问题选项卡,页面最顶部将出现一个蓝色加载栏,表示正在获取数据或依赖项,一旦完成它就会渲染下一条路线。我该怎么做呢?

我想我应该使用某种中间件,所以在路由更改之前,我应该调度一个操作来获取我需要的依赖项,然后一旦完成,我应该调度一个操作来更新 redux 存储的某些部分,我找不到将中间件应用到 react-router 的方法,我真的不知道从哪里开始以及如何开始。

3个回答

这是一个没有 redux 的例子:

我的页面.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
        })
    }
}

路由.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>

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

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>
  )
 }
}

如果您使用的是普通的 redux 和路由器,则可以使用路由器的生命周期函数,例如onEnter(在进入视图之前调用)或onLeave ...,然后您可以做任何您喜欢的事情,并且在您调用它时接受回调函数,实际路由发生。

另一种选择是使用一些 redux promise 中间件来处理异步作业,例如redux-promise-middleware或简单地使用loadbar(因为我们在生产中使用它们)进行thunk这与异步操作完美配合。

Redux Promise 中间件

React Redux 加载栏