browserHistory undefined(反应路由器v3)

时间:2017-06-01 12:35:49

标签: reactjs dom router

我正在努力与反应路由器,因为当我试图推动它时它返回“browserHistory未定义”。这是我的路线:

import React, { Component } from 'react';
import './App.css';
import UI from './UI.jsx';
import Home from './Home';
import Login from './Login';
import { browserHistory} from 'react-router';
import { BrowserRouter as Router, Route, Link} from 'react-router-dom';



class App extends Component {

 render() {

   return (

     <div>

     <Router history={browserHistory}>
       <div>
         <Route exact path="/" component={Home}/>
         <Route path="/UI" component={UI}/>
       </div>
     </Router>



     </div>
   );
 }
}

export default App;

这是我使用browserHistory.push()的文档。功能:

login(e) {
       console.log(this.props.browserHistory);
       e.preventDefault();
       var username = this.inputName.value;
       var password = this.inputPassword.value;
       axios.post(
           'https://jsonplaceholder.typicode.com/posts',
           {
               user_name: username,
               user_password: password
           }
       ).then((response) => {
           console.log(response.data);
           console.log(response.data.user_name);
           const username = response.data.user_name;
           session = "&token=" + response.data.session;
           if (username === null) {
               this.setState({ loginFail: 'Användarnamnet eller lösenordet är fel' });
               return;
           } else {
               browserHistory.push('/UI');  //The UI is the component, here i'm getting "cannot read property push of undefined".

               this.setState({
                   showUser: `Hej ${response.data.user_name}`,
                   showLogin: !this.state.showLogin,
                   loggedIn: !this.state.loggedIn
               });   
           }
       });
   }

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

您必须通过说

将其分配给变量

const { browserHistory } = this.props然后你可以browserHistory.push('/UI');

或者只使用this.props.browserHistory.push('/UI')

答案 1 :(得分:0)

感谢您的快速回复。虽然还有一些麻烦。我会发布一个img的。 enter image description here

答案 2 :(得分:0)

根据documentation您需要做的是:

import { browserHistory } from 'react-router';
browserHistory.push('/UI');