reactjs - 我获取 this.props.children 里面的数据;
问题描述
我是新手,我有一个很好的登录功能,但我需要使用 this.props.children 为下一页发送有关用户的信息。我希望你能帮助我我的路线中的鳕鱼是下一个
<BrowserRouter>
<Switch>
<Route path="/" exact component={Carrousel} />
<Route path="/registro" component={Register} exact/>
<Route path="/login" component={Login} exact/>
<Route path="/contact" component={Contact} exact/>
<AuthComponent>
<Route path="/protected" component={Protected} exact />
</AuthComponent>
</Switch>
</BrowserRouter>
我在 authComponent 中用于登录的代码
import React, {Component} from 'react';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
class AuhtComponent extends Component{
constructor(props){
super(props);
this.state={
user: undefined
}
}
componentDidMount(){
this.getUser();
}
getUser() {
const jwt = getJwt();
if (!jwt) {
this.setState({
user: null
});
return;
}
axios.get('getUser', { headers: { Authorization: `Bearer ${jwt}`} }).then(res => {
this.setState({
user: res.data
})
});
}
render(){
const { user } = this.state;
if (user === undefined) {
return (
<div>
Loading...
</div>
);
}
if (user === null) {
this.props.history.push('/login');
}
return this.props.children;
}
}
export default withRouter(AuhtComponent);
现在我想恢复受保护的 nex 组件中的信息,但我
import React, {Component} from 'react';
class Inicio extends Component{
render(){
return(
<h1>{this.state.user}</h1>
)
}
}
欢迎任何帮助
解决方案
您应该使用 HOC(高阶组件):
工作版链接:
https://codesandbox.io/s/busy-booth-hwllz
代码:
const withAuth = WrappedComponent =>
class extends React.Component {
constructor(props){
super(props);
this.state={
user: undefined
}
}
componentDidMount(){
this.getUser();
}
getUser() {
const jwt = getJwt();
if (!jwt) {
this.setState({
user: null
});
return;
}
axios.get('getUser', { headers: { Authorization: `Bearer ${jwt}`} }).then(res => {
this.setState({
user: res.data
})
});
}
render(){
const { user } = this.state;
if (user === undefined) {
return (
<div>
Loading...
</div>
);
}
if (user === null) {
this.props.history.push('/login');
}
return <WrappedComponent {...this.props} user={user}/>;
}
};
export default withAuth;
并像这样使用它:
<BrowserRouter>
<Switch>
<Route path="/" exact component={Carrousel} />
<Route path="/registro" component={Register} exact/>
<Route path="/login" component={Login} exact/>
<Route path="/contact" component={Contact} exact/>
<Route path="/protected" component={withAuth(Protected)} exact />
</Switch>
</BrowserRouter>
推荐阅读
- amazon-web-services - AWS Apigateway + 简单系统管理 + 集成
- corda - 如果我 uploadAttachmentWithMetadata 为什么我看不到 CRaSH shell 中使用“attachments trustInfo”的附件
- reactjs - React 上下文提供程序不显示默认值
- javascript - 是否应该将 refs 列为 useEffect 等的依赖项?
- touchscreen - Windows 7 Embedded 上的触摸屏
- python - 环境变量好像有问题——Python
- git - 如何在命名 GitHub 存储库时包含 [ ](方括号)?
- c# - 是否可以直接路由到托管在 MVC 应用程序中的 blazor 页面?
- c - 仅当我在调试模式下运行程序时,程序才会收到 SIGSEGV(分段错误)信号
- ios - UITableView 破坏性上下文菜单动画