简体   繁体   English

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

[英]React router - undefined history

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. 我试图使用1.0.0-rc1 react-router和历史2.0.0-rc1按下按钮后手动浏览网站。 Unfortunately, after pressing the button I get: 不幸的是,按下按钮后我得到:

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.history everything works fine. 当我使用this.props.history历史时一切正常。 What is the problem with this code? 这段代码有什么问题?

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/testapp and everything worked fine - my static resources are generated into dist/testapp directory. 之前(没有history = {history}),我刚刚访问了localhost:8080/testapp ,一切正常 - 我的静态资源被生成到dist/testapp目录中。 Now under this URL I get: 现在在这个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`) }, 

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 / 不能获取 /

As of "react-router": "^4.1.1" , you may try the following: “react-router”:“^ 4.1.1”开始 ,您可以尝试以下方法:

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

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). .. 然后'React Router'将为此组件添加一个名为'history'的新属性 (在本例中为LoginScreen)。 You can use this history prop to programatically navigate to other rountes. 您可以使用此历史记录以编程方式导航到其他rountes。

So now in the LoginScreen component you can navigate like this: 所以现在在LoginScreen组件中,您可以像这样导航:

2: LoginScreen: 2:LoginScreen:

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
}

Because everything changes like hell in react world here's a version which worked for me at December 2016: 因为一切都像反应世界中的地狱一样变化,这是一个在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

To create browser history you now need to create it from the History package 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 docs explain this perfectly 文档完美地解释了这一点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM