当某些条件返回null或false,但未触发重定向操作时,我希望重定向到主页。
import { Link, Redirect } from "react-router-dom";
if(localStorage.getItem("example") === null || localStorage.getItem("example") === false){
return <Redirect to="/" />
}我将这段代码放在一个在OnClick和componentDidMount()中触发的简单函数中,但它不起作用。
发布于 2019-04-17 15:16:20
您可以使用重定向到主页,这是基于可以通过在onClickHandler或handleSubmit中使用setState更改的重定向标志。
import { Redirect } from "react-router-dom";
class MyComponent extends React.Component {
state = {
redirect: false
}
handleSubmit () {
if(localStorage.getItem("example") === null || localStorage.getItem("example") === false){
return this.setState({ redirect: true });
}
}
render () {
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/'/>;
}
return <YourForm/>;
}发布于 2019-04-17 15:21:58
你需要在render中使用重定向。它是一个React组件,用于呈现用户,然后将用户发送到所需的路径:
import React, { Component } from "react";
import { Route, Switch, Redirect } from "react-router-dom";
class RootPage extends React.Component {
state = {
isLoggedOut: false
};
onClick = () => {
this.setState({
isLoggedOut: true
});
};
render() {
return (
<div>
{this.state.isLoggedOut && <Redirect to="/logout" />}
<button onClick={this.onClick}>Logout</button>
</div>
);
}
}
const Log = () => <h1>Logout</h1>;
class App extends Component {
render() {
return (
<div>
<nav className="navbar navbar" />
<Switch>
<Route exact path="/" component={RootPage} />
<Route exact path="/logout" component={Log} />
</Switch>
</div>
);
}
}
export default App;当您单击注销按钮时,它会将您重定向到rootPath。
发布于 2019-04-17 15:24:27
看看官方文档中的this example吧。
如果使用类组件,<Redirect />应该在render方法中。或者,如果你使用一个函数组件,它应该在它返回的内容中。
示例如下:
import { Component } from 'react';
const PrivateComponent = (props) => {
return(
localStorage.getItem("example")
? <RandomComponent />
: <Redirect to="/signin" />
)
}https://stackoverflow.com/questions/55721797
复制相似问题