对于想了解如何在ReactRouterv4中推送到历史记录?的读者,本文将是一篇不可错过的文章,我们将详细介绍reactrouterhistory,并且为您提供关于javascript–如何在新的Re
对于想了解如何在React Router v4中推送到历史记录?的读者,本文将是一篇不可错过的文章,我们将详细介绍react router history,并且为您提供关于javascript – 如何在新的React Router v4中访问历史对象、React Router v4 baseName和自定义历史记录、React Router失败的道具“历史记录”,未定义、React Router找不到历史记录的有价值信息。
本文目录一览:- 如何在React Router v4中推送到历史记录?(react router history)
- javascript – 如何在新的React Router v4中访问历史对象
- React Router v4 baseName和自定义历史记录
- React Router失败的道具“历史记录”,未定义
- React Router找不到历史记录
如何在React Router v4中推送到历史记录?(react router history)
在当前版本的React
Router(v3)中,我可以接受服务器响应并用于browserHistory.push
转到相应的响应页面。但是,这在v4中不可用,我不确定哪种适当的处理方式。
在此示例中,使用Redux,当用户提交表单时, components / app-product-form.js
调用this.props.addProduct(props)
。服务器返回成功后,该用户将被带到“购物车”页面。
// actions/index.jsexport function addProduct(props) { return dispatch => axios.post(`${ROOT_URL}/cart`, props, config) .then(response => { dispatch({ type: types.AUTH_USER }); localStorage.setItem(''token'', response.data.token); browserHistory.push(''/cart''); // no longer in React Router V4 });}
如何从React Router v4的功能重定向到购物车页面?
答案1
小编典典您可以在history
组件外部使用这些方法。通过以下方式尝试。
首先,history
使用历史记录包创建一个对象:
// src/history.jsimport { createBrowserHistory } from ''history'';export default createBrowserHistory();
然后将其包装<Router>
( 请注意 ,您应该使用import { Router }
而不是import { BrowserRouteras Router }
):
// src/index.jsx// ...import { Router, Route, Link } from ''react-router-dom'';import history from ''./history'';ReactDOM.render( <Provider store={store}> <Router history={history}> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/login">Login</Link></li> </ul> <Route exact path="/" component={HomePage} /> <Route path="/login" component={LoginPage} /> </div> </Router> </Provider>, document.getElementById(''root''),);
从任何地方更改当前位置,例如:
// src/actions/userActionCreators.js// ...import history from ''../history'';export function login(credentials) { return function (dispatch) { return loginRemotely(credentials) .then((response) => { // ... history.push(''/''); }); };}
UPD :您还可以在React Router FAQ中看到一个稍微不同的示例。
javascript – 如何在新的React Router v4中访问历史对象
所以我有history.js看起来像这样
import { createbrowserHistory } from 'history'; export default createbrowserHistory;
我的index.js
render(( <Router history={history}> <div> <Route component={App}/> </div> </Router> ),document.getElementById('root') );
Home.js看起来像这样
class Home extends Component { handleSubmit(e) { e.preventDefault(); let teacherName = e.target.elements[0].value; let teacherTopic = e.target.elements[1].value; let path = `/featured/${teacherName}/${teacherTopic}`; history.push(path); } render() { return ( <div className="main-content home"> <hr /> <h3>Featured Teachers</h3> <form onSubmit={this.handleSubmit}> <input type="text" placeholder="Name"/> <input type="text" placeholder="Topic"/> <button type="submit"> Submit </button> </form> </div> ); } } export default Home;
Home.js实际上是在app.js中路由的,它在index.js中路由.
问题是我无法在任何地方访问历史对象.
我尝试过的方法如下
1)home.js中的this.context.history.push(path) – 无法访问undefined的上下文
2)home.js中的this.props.history.push(path) – 无法访问undefined的道具
3)index.js中的browserHistory.push(path) – 现在已弃用
4)上面的方式 – _history2.default.push不是一个函数
我上面尝试的所有方法都不起作用.第二个是最奇怪的,因为我应该能够根据文档https://reacttraining.com/react-router/web/api/Route/Route-render-methods在任何地方访问历史对象作为道具
我知道以前的v2或v3访问历史记录的方式也已弃用.
那么知道如何在React Router v4中访问历史对象的人能回答这个问题吗?谢谢.
解决方法
... import { withRouter } from 'react-router' class Home extends Component { functionMethod() { const { history: { push } } = this.props; doStuff(); push('/location'); } ... } export default withRouter(Home);
https://reacttraining.com/react-router/web/api/withRouter
React Router v4 baseName和自定义历史记录
我想为我的路线分配一个基本名称,我可以使用BrowserRouter为其指定一个名称。
但是,我也想指定一个自定义历史记录,以便可以以编程方式导航我的用户。我可以用路由器做。
但是,我不能两者都做。是否可以扩展其中一个路由器以支持此功能或将功能环绕它以添加此功能?
我当前的设置是-
import React from ''react'';import { Router, Switch, Route, Redirect } from ''react-router-dom'';import createHistory from ''./history'';import Navigation from ''./components/navigation/Navigation'';import PrivateRoute from ''./components/private-route/PrivateRoute'';import Home from ''./containers/home/Home'';import PageTwo from ''./components/pageTwo/PageTwo'';import Callback from ''./components/callback/Callback'';import Login from ''./components/login/Login'';export default () => ( <Router history={createHistory}> <div> <Navigation /> <Switch> <Route path="/callback" component={Callback} /> <Route path="/login" component={Login} /> <PrivateRoute path="/" exact component={Home} /> <PrivateRoute path="/page-two" component={PageTwo} /> <Redirect to="/" /> </Switch> </div> </Router>);
但是我很想实现以下目标:
<Router history={createHistory} basename="foo">
答案1
小编典典您可以:
<BrowserRouter basename="/your/app"> <App/></BrowserRouter>
或直接配置history
对象:
import { Router } from ''react-router'';import createBrowserHistory from ''history/createBrowserHistory'';const history = createBrowserHistory({ basename: ''/your/app'' });<Router history={history}> <App /></Router>
React Router失败的道具“历史记录”,未定义
我一直在跟踪Tyler Mcginnis的教程,并用React
Router遇到了麻烦,尤其是历史记录。我最终逐字复制了他的代码只是为了看看是否只有我一个人,但我仍然
Warning: React.createElement: type is invalid -- expected a string (for built-
in components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file it's
defined in.
Warning: Failed prop type: The prop `history` is marked as required in
`Router`,but its value is `undefined`. in Router
Uncaught TypeError: Cannot read property 'location' of undefined
at new Router (index_bundle.js:8347)
at index_bundle.js:19079
at measureLifeCyclePerf (index_bundle.js:18859)
at ReactCompositeComponentWrapper._constructComponentWithoutOwner (index_bundle.js:19078)
at ReactCompositeComponentWrapper._constructComponent (index_bundle.js:19064)
at ReactCompositeComponentWrapper.mountComponent (index_bundle.js:18972)
at Object.mountComponent (index_bundle.js:4070)
at ReactCompositeComponentWrapper.performInitialMount (index_bundle.js:19155)
at ReactCompositeComponentWrapper.mountComponent (index_bundle.js:19042)
at Object.mountComponent (index_bundle.js:4070)
实现是:
var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var hashHistory = ReactRouter.hashHistory;
var IndexRoute = ReactRouter.IndexRoute;
var Main = require('../components/Main');
var Home = require("../components/Home");
var PromptContainer = require('../containers/PromptContainer');
var routes = (
<Router history={hashHistory}>
<Route path='/' component={Main}>
<IndexRoute component={Home} />
<Route path='playerOne' header='Player One' component={PromptContainer} />
<Route path='playerTwo/:playerOne' header='Player Two' component={PromptContainer} />
</Route>
</Router>
);
module.exports = routes;
我注意到的是模块hashHistory
中不存在react-
router
,而是模块createBrowserHistory
内部history
。遵循找到的API文档,我认为必须通过以下位置调用它:
var BrowserHistory = require('history/createBrowserHistory);
const history = createBrowserHistory();
这样做会产生createBrowserHistory is not a
function
错误。删除括号,会导致与上述历史记录相同的错误undefined
。
当我记录历史记录时,绝对是不确定的,这使我相信问题与import语句有关,但是控制台不会告诉我ReactRouter.hashHistory
找不到吗?
我知道本教程已经使用一年了,我可能还不知道对API所做的更改,这就是我的问题所在。任何帮助表示赞赏!
React Router找不到历史记录
文档对此一无所获,但就我而言,该问题通过安装历史记录来解决:npm install --save history
问题可能出在从react-router
的{{1}}而不是react-router-dom
的{{1}}
今天关于如何在React Router v4中推送到历史记录?和react router history的分享就到这里,希望大家有所收获,若想了解更多关于javascript – 如何在新的React Router v4中访问历史对象、React Router v4 baseName和自定义历史记录、React Router失败的道具“历史记录”,未定义、React Router找不到历史记录等相关知识,可以在本站进行查询。
本文标签: