我想重定向到“/ user”。我写但这不起作用。 如何正确地重定向到正确的页面
onClick = (e) => {
this.setState({ errorLoad: false});
getPlayerInfo(this.state.id).then(data => {
if(data.success == false) {
this.setState({ errorLoad: true});
return;
}
this.setState({ user: data.player});
console.log(data);
<Redirect to="/user"/>
});
}
我的路由器列表。其中有一个路径为“/ user”的路由器
<Route path="/user" render={(props) => <User {...props} user={this.state.user} />} />
UPADATE
App.js
我点击的按钮位于组件<SearchForm/>
render() {
let style = {marginLeft: '20px'};
return (
<div>
<Header source='https://www.shareicon.net/data/2017/02/15/878753_media_512x512.png'/>
<SearchForm onClick={this.onClick} style={style} onChange={this.onHandle} placeholder="search"/>
<Centered style={ {marginTop: '50px'} }>
<BrowserRouter>
<Switch>
<Route exact path='/' component={Startup} />
<Route path="/user" render={(props) => <User {...props} user={this.state.user} />} />
</Switch>
</BrowserRouter>
</Centered>
</div>
);
}
答案 0 :(得分:2)
您需要使用this.props.history
手动重定向:
onClick = (e) => {
this.setState({ errorLoad: false});
getPlayerInfo(this.state.id).then(data => {
if(data.success == false) {
this.setState({ errorLoad: true});
return;
}
this.setState({ user: data.player});
console.log(data);
this.props.history.push('/user');
});
}
您应该从history
组件获取<Router>
作为道具。
修改强>
好的,谢谢您的代码更新。 SearchForm组件没有嵌套在您的BrowserRouter下,因此它没有得到历史记录。在BrowserRouter中移动该组件或在SearchForm中使用withRouter HOC reacttraining.com/react-router/web/api/withRouter
选项1:在SearchForm
BrowserRouter
render() {
let style = {marginLeft: '20px'};
return (
<div>
<Header source='https://www.shareicon.net/data/2017/02/15/878753_media_512x512.png'/>
<Centered style={ {marginTop: '50px'} }>
<BrowserRouter>
<SearchForm onClick={this.onClick} style={style} onChange={this.onHandle} placeholder="search"/>
<Switch>
<Route exact path='/' component={Startup} />
<Route path="/user" render={(props) => <User {...props} user={this.state.user} />} />
</Switch>
</BrowserRouter>
</Centered>
</div>
);
}
选项2:使用withRouter
HOC手动将history
道具注入SearchForm
:
import { withRouter } from 'react-router-dom';
class SearchForm extends React.Component { ... }
export default withRouter(SearchForm)
答案 1 :(得分:2)
有两种方法可以使用React Router进行编程导航 - <Redirect />
和history.push
。您使用的主要取决于您和您的具体用例。
<Redirect />
顺序使用 user event -> state change -> re-render
。
此方法的缺点是您需要在组件的状态上创建新属性,以便知道何时呈现重定向。这是有效的,但同样,这几乎是React的重点 - 状态更改会更新UI。
React Router真正的工作是History
库。在引擎盖下,它正在跟踪React Router的会话历史记录。当组件由React Router呈现时,该组件将传递三个不同的道具:location
,match
和history
。这个history
道具来自History
库,并且在路由方面有很多花哨的属性。在这种情况下,我们感兴趣的是history.push
。它的作用是将新条目推送到历史堆栈 - 也就是将用户重定向到另一条路径。