我是React的新手,并且在使用JavaScript事件处理程序重定向到新页面时遇到问题。我不知道我做错了什么。App.jsimport 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.jsimport 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 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
Redirect组件需要呈现而不返回到onClick处理程序,这就是它不起作用的原因。您可以history.push代替
gotoURL(usr){
let url = `/user/${usr}`;
//console.log(url);
this.props.history.push(url);
}
添加回答
举报
0/150
提交
取消