【发布时间】:2021-07-24 17:55:16
【问题描述】:
我无法通过react-router 重定向到“/”路径。我的App.jsx 文件如下所示:
ReactDOM.render(<Router>
<Switch>
<Route exact path="/" component={Content} />
<Route path="/login" component={Auth} />
{/* <Route component={NotFound} /> */}
</Switch>
</Router>, document.getElementById("root"));
添加 这是我的身份验证组件,它决定了重定向登录或注册的身份验证表单:
export default class Auth extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoginActive: true,
};
this.formChange = this.formChange.bind(this);
}
formChange() {
this.setState({ isLoginActive: !this.state.isLoginActive });
}
render() {
const { isLoginActive } = this.state;
let view = isLoginActive ? (
<Login apiUrl={apiUrl} formChange={this.formChange} history={this.props.history} />
) : (
<Register apiUrl={apiUrl} formChange={this.formChange} history={this.props.history} />
);
return (
<div className="container">
{getCookie("token") == null ? view : <Redirect to="/" />}
</div>
);
}
}
这里是登录组件,在成功的 axios 请求上重定向到链接到内容组件的“/”路径
export default class Login extends React.Component {
//constructor
login() {
// axios request
this.setState({ userLoggedIn: true });
}
render() {
return this.state.userLoggedIn ? (
<Redirect exact to="/" />
) : (
<div className="base-container">
<button type="button" className="btn" onClick={this.login}>
Login
</button>
</div>
</div>
);
}
}
如果我在这里将<Redirect exact to="/" /> 的路线更改为任何其他路线,例如'/home',一切都会完美运行。所以我不能重定向到'/'路由。
【问题讨论】:
标签: reactjs redirect react-router