我正在尝试有条件地渲染代码块。条件canProject
可以为true或false。这可以通过checkRole()
函数进行评估。
问题是checkRole()
返回了诺言。到兑现承诺时,内容已经呈现出来。
如何使用checkRole()
有条件地渲染代码块?注意,我在html代码的很多地方都使用了canProject
条件,因此我想根据需要在return (
中通过添加{canProject &&
render() {
const canProject = checkRole('project'); //this returns a promise
return (
<div>
<div className="row">
{canProject &&
<div className="col-lg-4">
</div>
}
</div>
</div>
);
}
答案 0 :(得分:2)
跟踪承诺状态:
this.state = {
promiseFulfilled: false
}
const canProject = checkRole('project').then(() => this.setState({promiseFulfilled: true}))
render() {
const { promiseFulfilled } = this.state
if (promiseFulfilled) {
return (
<div>
<div className="row">
{canProject &&
<div className="col-lg-4">
</div>
}
</div>
</div>
)
} else {
return null
}
}
为了后代:这是使用hooks使用更新版本的React(版本> 16.8)的正确方法:
const [ promiseFulfilled, setPromiseFulfilled ] = useState(false)
const canProject = checkRole('project').then(() => setPromiseFulfilled(true))
render() {
if (promiseFulfilled) {
return (
<div>
<div className="row">
{canProject &&
<div className="col-lg-4">
</div>
}
</div>
</div>
)
} else {
return null
}
}
答案 1 :(得分:0)
我认为这是实现这一目标的最优雅的方式:
constructor() {
super();
this.state = {canProjectR: false}; //set to false initally
}
//set the canProjectR to the response which is true or false
componentDidMount() {
this.checkRole('project').then(res => { this.setState({ canProjectR: res}) });
}
//use this.state.canProject && as needed
render() {
return (
<div>
<div className="row">
{this.state.canProject &&
<div className="col-lg-4">
</div>
}
</div>
</div>
);
}