React v4,URL从事件处理程序重定向

时间:2019-04-08 12:21:58

标签: javascript reactjs react-router

我是新来的人,我在使用javascript事件处理程序重定向到新页面时遇到了问题。我不知道我做错了什么,请有人帮忙。

App.js

import React, { Component } from 'react';
import {Switch, Route} from 'react-router-dom';

import Nav, {Jumbotron} from '../partials/headobjs';
import Footer from '../partials/footer';
import Users from '../components/user';
import UserObj from '../components/userobj';
import Err404 from '../components/err404';

//import css files.. 
import '../css/styles.css';


class App extends Component {
  render() {
    return (
      <div>
          <Nav />      
          <Jumbotron/>   

          <Switch>
            <Route exact path='/' component={Users}/>
            <Route path='/user' component={UserObj}/>
            <Route component={Err404} />
          </Switch>

          <div className='clr'></div>

          <Footer />
      </div>      
    );
  }
}

export default App;

Users.js

import React, { Component } from 'react';
import {Redirect} from 'react-router-dom';

class Users extends Component {

  constructor(){
    super();
    this.state = { 
      name:aminu
    };
  }

  gotoURL(usr){
    let url = `/user/${usr}`;
    //console.log(url);
    return <Redirect to={url}/>
  }

  render() {    
     return (    
        <div className="container">
             <button onClick={this.gotoURL.bind(this, this.state.name)}>
               Go to {this.state.name} page
            </button>
        </div>
    );
  }
}

export default Users;

我希望函数gotoURL重定向到新路由,但是我不确定自己做错了什么,我尝试使用browserHistory,现在我正在尝试<Redirect/>类,但无济于事。

有人可以帮我吗。谢谢。

3 个答案:

答案 0 :(得分:4)

Redirect组件需要呈现,并且不返回给onClick处理程序,这就是它不起作用的原因。您可以改用history.push

gotoURL(usr){
    let url = `/user/${usr}`;
    //console.log(url);
    this.props.history.push(url);
  }

答案 1 :(得分:1)

Instead of redirect from function, use render method and state to workout with redirect problem

class Users extends Component {

    constructor(){
        super();
        this.state = {
            name:'aminu',
            toUser: false
        };
    }

    gotoURL(usr){
        let url = `/user/${usr}`;
        //console.log(url);
        this.setState({toUser:true, goto: url})
    }

    render() {

        if (this.state.toUser === true) {
            return <Redirect to={this.state.goto}/>
        }

        return (
            <div className="container">
                <button onClick={this.gotoURL.bind(this, this.state.name)}>
                    Go to {this.state.name} page
                </button>
            </div>
        );
    }
}

答案 2 :(得分:0)

您可以使用react-v4中的链接组件来更改您的路线。

import { Link } from 'react-router-dom';

<div className="container">
    <Link to={`/user/${usr}`}
        <button>
          Go to {this.state.name} page
        </button>
    </Link>
</div>