使用 Redux-Router + React-Router 向应用程序添加基本 URL [英] Adding a base URL to an app using Redux-Router + React-Router

查看:20
本文介绍了使用 Redux-Router + React-Router 向应用程序添加基本 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React-Router 1.0.0-rc3 和 Redux-Router 1.0.0-beta3.

I'm using React-Router 1.0.0-rc3 together with Redux-Router 1.0.0-beta3.

在使用 React-Router 时,您可以使用 useBasenamecreateHistory 来设置应用程序的基本 URL,这样您就可以轻松编写在内部运行的应用程序子目录.示例:

When using React-Router, you can use useBasename with createHistory to set the base URL for an app, so that you can easily write an app that runs inside a subdirectory. Example:

取而代之的是:

import { createHistory } from 'history';

let base = "/app_name/"

<Router history={browserHistory}>
  <Route path={base} component={App}></Route>
</Router>

<Link path={base + "some_path"}>some_path</Link>

您可以使用 useBasename 以这种方式编写:

You can write in this way using useBasename:

import { createHistory, useBasename } from 'history';

const browserHistory = useBasename(createHistory)({
  basename: "/app_name"
});

<Router history={browserHistory}>
  <Route path="/" component={App}></Route>
</Router>

<Link path="/some_path">some_path</Link>

但是,在 Redux-Router 中,您需要将 createHistory 而不是 history 传递给 reducer:

However, in Redux-Router, you need to pass createHistory instead of history to a reducer:

const store = compose(
  applyMiddleware(m1, m2, m3),
  reduxReactRouter({
    routes,
    createHistory
  }),
  devTools()
)(createStore)(reducer);

在这种情况下我们如何使用useBasename?

How can we use useBasename in this case?

推荐答案

对于 react-router v2 或 v3 并使用 react-router-redux v4 而不是 redux-router,历史对象的设置将如下所示:

For react-router v2 or v3 and using react-router-redux v4 instead of redux-router, the setup of the history object will look like this:

import { createHistory } from 'history'
import { useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'

const browserHistory = useRouterHistory(createHistory)({
  basename: '<yourBaseUrl>'
})
const history = syncHistoryWithStore(browserHistory, store)

当没有额外的基本 URL 时,其余设置与往常一样.

The rest of the setup is as usual when there is no extra base URL.

这篇关于使用 Redux-Router + React-Router 向应用程序添加基本 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆