我有组件Login
:
class Login extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: false
};
并希望从其他文件isAuthenticated
访问routes.js
:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={() => (
Login.state.isAuthenticated === true
? <Component {...this.props}/>
: <Redirect to="/" />
)}/>
)
export default () => (
<BrowserRouter>
<div>
<Navbar />
<Switch>
<Route path="/" exact component={Login} />
<Route path="/register" exact component={Register} />
<PrivateRoute path="/home" exact component={Home} />
</Switch>
</div>
</BrowserRouter>
);
我该怎么做呢?这个路由文件叫什么?它是另一个“组件”吗?我是否需要以某种方式将状态从Login
传递为props
?
答案 0 :(得分:2)
它的要点是父组件必须具有状态,因为父组件不能触及子组的状态。有几种方法可以实现您的目标:
Login
即可控制对父级状态的访问Login
渲染PrivateRoute
1的一些建议:
class App extends React.Component {
constructor() {
super()
this.state = { isAuthenticated: false }
}
setAuthenticated = (isAuthenticated) => {
this.setState({ isAuthenticated })
}
render() {
return (
<BrowserRouter>
<div>
<Navbar />
<Switch>
<Route path="/" exact component={() =>
<Login
isAuthenticated={this.state.isAuthenticated}
setAuthenticated={this.setAuthenticated}/>}/>
<Route path="/register" exact component={Register} />
<PrivateRoute path="/home" exact component={Home} />
</Switch>
</div>
</BrowserRouter>)
}
}
然后需要更改Login
以提取isAuthenticated
的值并使用道具中的setAuthenticated
函数。