Javascript 反应路由器 - 未定义的历史

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34595890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:36:48  来源:igfitidea点击:

React router - undefined history

javascriptreactjsecmascript-6react-router

提问by Niemand

I am trying to use the 1.0.0-rc1 react-router and history 2.0.0-rc1 to navigate manually through the website after pressing the button. Unfortunately, after pressing the button I get:

我正在尝试使用 1.0.0-rc1 react-router 和 history 2.0.0-rc1 在按下按钮后手动浏览网站。不幸的是,按下按钮后,我得到:

Cannot read property 'pushState' of undefined

无法读取未定义的属性“pushState”

My router code:

我的路由器代码:

import React from 'react';
import { Router, Route, Link, browserHistory } from 'react-router'
import AppContainer from './components/AppContainer.jsx';
import MyTab from './components/test/MyTab.jsx';
import MainTab from './components/test/MainTab.jsx';


var routes = (
    <Route component={AppContainer} >
        <Route name="maintab" path="/" component={MainTab} />
        <Route name="mytab" path="/mytab" component={MyTab} />
    </Route>
);

React.render(<Router history={browserHistory}>{routes}</Router>, document.getElementById('main'));

The navigation button is on MyTab and it attemps to navigate to MainTab:

导航按钮位于 MyTab 上,它尝试导航到 MainTab:

import React from 'react';
import 'datejs';
import History from "history";
export default React.createClass({

    mixins: [ History ],

    onChange(state) {
        this.setState(state);
    },

    handleClick() {
        this.history.pushState(null, `/`)
    },

    render() {
        return (
            <div className='container-fluid' >
                <button type="button" onClick={this.handleClick.bind(this)}>TEST</button>
            </div>

        );
    }
});

When I use history with this.props.historyeverything works fine. What is the problem with this code?

当我使用历史时this.props.history一切正常。这段代码有什么问题?

EDIT.

编辑。

After adding the following:

添加以下内容后:

const history = createBrowserHistory();

React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));

I try to access my app. Before (without history={history}), I just accessed localhost:8080/testappand everything worked fine - my static resources are generated into dist/testappdirectory. Now under this URL I get:

我尝试访问我的应用程序。之前(没有 history={history}),我刚刚访问localhost:8080/testapp并且一切正常 - 我的静态资源生成到dist/testapp目录中。现在在这个 URL 下我得到:

Location "/testapp/" did not match any resources

位置“/testapp/”没有匹配任何资源

I tried to use the useBasename function in a following way:

我尝试通过以下方式使用 useBasename 函数:

    import { useBasename } from 'history'
    const history = useBasename(createBrowserHistory)({
    basename: '/testapp'
});

React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));

and the application is back, but again I get the error

应用程序又回来了,但我再次收到错误

Cannot read property 'pushState' of undefined

无法读取未定义的属性“pushState”

in the call:

在通话中:

handleClick() {
    this.history.pushState(null, `/mytab`)
},
handleClick() {
    this.history.pushState(null, `/mytab`)
},

I thougt it may be because of my connect task in gulp, so I have added history-api-fallback to configuration:

我认为这可能是因为我在 gulp 中的连接任务,所以我在配置中添加了 history-api-fallback:

settings: {
      root: './dist/',
      host: 'localhost',
      port: 8080,
      livereload: {
        port: 35929
      },
      middleware: function(connect, opt){
        return [historyApiFallback({})];
      }
    }

But after adding middleware all I get after accessing a website is:

但是在添加中间件后,我访问网站后得到的只是:

Cannot GET /

不能获取 /

采纳答案by Santosh Pillai

As of "react-router": "^4.1.1", you may try the following:

"react-router": "^4.1.1" 开始,您可以尝试以下操作:

Use 'this.props.history.push('/new-route')'. Here's a detailed example

使用' this.props.history.push('/new-route')'。这是一个详细的例子

1: Index.js

1:Index.js

 import { BrowserRouter, Route, Switch } from 'react-router-dom'; 
 //more imports here
    ReactDOM.render(
      <div>
        <BrowserRouter>
           <Switch>
              <Route path='/login' component={LoginScreen} />
              <Route path='/' component={WelcomeScreen} />
           </Switch>
        </BrowserRouter>
     </div>, document.querySelector('.container'));

Above, we have used BrowserRouter, Route and Switch from 'react-router-dom'.

上面,我们使用了来自“react-router-dom”的 BrowserRouter、Route 和 Switch。

So whenever you add a component in the React Router 'Route', that is,

所以每当你在 React Router 'Route' 中添加一个组件时,也就是,

<Route path='/login' component={LoginScreen} />

..then 'React Router' will add a new property named 'history' to this component(LoginScreen, in this case). You can use this history prop to programatically navigate to other rountes.

..然后'React Router' 将向这个组件(在本例中为LoginScreen)添加一个名为'history' 的新属性。您可以使用此历史道具以编程方式导航到其他路线。

So now in the LoginScreen component you can navigate like this:

所以现在在 LoginScreen 组件中,您可以像这样导航:

2: LoginScreen:

2:登录屏幕:

return (
      <div>
       <h1> Login </h1>
       <form onSubmit={this.formSubmit.bind(this)} >
         //your form here
       </form>
      </div>

    );



formSubmit(values) {
 // some form handling action
   this.props.history.push('/'); //navigating to Welcome Screen
}

回答by holms

Because everything changes like hell in react world here's a version which worked for me at December 2016:

因为在 React 世界中一切都像地狱一样变化,这里有一个在 2016 年 12 月对我有用的版本:

import React from 'react'
import { Router, ReactRouter, Route, IndexRoute, browserHistory } from 'react-router';

var Main = require('../components/Main');
var Home = require('../components/Home');
var Dialogs = require('../components/Dialogs');

var routes = (
    <Router history={browserHistory}>
        <Route path='/' component={Main}>
            <IndexRoute component={Home} />
            <Route path='/dialogs' component={Dialogs} />
        </Route>
    </Router>
);

module.exports = routes

回答by Henrik Andersson

To create browser history you now need to create it from the Historypackage much like you've tried.

要创建浏览器历史记录,您现在需要History像您尝试过的那样从包中创建它。

import createBrowserHistory from 'history/lib/createBrowserHistory';

and then pass it to the Router like so

然后像这样将它传递给路由器

<Router history={createBrowserHistory()}>
    <Route />
</Router>

The docsexplain this perfectly

文档完全解释这种

回答by s.chandran sha

 import React, { Component} from 'react';
 import { Link } from 'react-router-dom';
 class Login extends Component {
 constructor(props){
 super(props)
 }
 handleClick(event){
  this.props.history.push('/dashboard')
}
 render() {
  return (
         <Button color="primary" className="px-4"  onClick={this.handleClick.bind(this)}>Login</Button>
          )}
}