包装器 ReactJS
Wrapper ReactJS
我有一个包装器,它允许我在功能上扮演用户的角色去处理不同的组件。
我想在后者中添加一个角色,但我不知道如何(角色是这个 "parent")
如果你有想法我很感兴趣
这是我的包装纸:
export default class Wrapper extends Component {
constructor() {
super();
this.state = {
role: null
}
}
componentDidMount() {
let config = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${authentication.getToken()}`
}
}
axios.get(`http://rec.mylittlegeek.school/api/whoami`,
config).then(response => {
console.log(response);
this.setState({ role: response.data.role });
}).catch(error => {
console.log(error);
})
}
render() {
return !this.state.role ?
"Loading ..."
: this.state.role === "admin" ?
<GeekSessions {...this.props} />
:
<GeekDashSessions {...this.props} />
}
}
它不是最漂亮的,但我应该可以用。父角色的新 GeekParentSessions 组件。
return ({!this.state.role ?
"Loading ..."
: this.state.role === "admin" ?
<GeekSessions {...this.props} />
:
this.state.role === "parent" ?
<GeekParentSessions {...this.props} />
:
<GeekDashSessions {...this.props} />
})
我不建议在你的三元组中嵌套更多条件,只需使用经典的 if 来使其更具可读性:
render() {
const { role } = this.state;
if (!role) {
return <div>Loading ...</div>;
}
if (role === 'parent') {
return <GeekParentSessions {...this.props} />;
}
if (role === 'child') {
return <GeekChildSessions {...this.props} />;
}
return <GeekDashSessions {...this.props} />;
}
我有一个包装器,它允许我在功能上扮演用户的角色去处理不同的组件。 我想在后者中添加一个角色,但我不知道如何(角色是这个 "parent") 如果你有想法我很感兴趣
这是我的包装纸:
export default class Wrapper extends Component {
constructor() {
super();
this.state = {
role: null
}
}
componentDidMount() {
let config = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${authentication.getToken()}`
}
}
axios.get(`http://rec.mylittlegeek.school/api/whoami`,
config).then(response => {
console.log(response);
this.setState({ role: response.data.role });
}).catch(error => {
console.log(error);
})
}
render() {
return !this.state.role ?
"Loading ..."
: this.state.role === "admin" ?
<GeekSessions {...this.props} />
:
<GeekDashSessions {...this.props} />
}
}
它不是最漂亮的,但我应该可以用。父角色的新 GeekParentSessions 组件。
return ({!this.state.role ?
"Loading ..."
: this.state.role === "admin" ?
<GeekSessions {...this.props} />
:
this.state.role === "parent" ?
<GeekParentSessions {...this.props} />
:
<GeekDashSessions {...this.props} />
})
我不建议在你的三元组中嵌套更多条件,只需使用经典的 if 来使其更具可读性:
render() {
const { role } = this.state;
if (!role) {
return <div>Loading ...</div>;
}
if (role === 'parent') {
return <GeekParentSessions {...this.props} />;
}
if (role === 'child') {
return <GeekChildSessions {...this.props} />;
}
return <GeekDashSessions {...this.props} />;
}