我想根据某种情况显示一个视图,但是该视图根本没有出现。这是我的代码-
showView = async () => {
let isConditionFulfilled = await checkCondition();
console.log('isConditionFulfilled' + isConditionFulfilled)
return isConditionFulfilled;
}
render() {
return (
<View>
{this.showView() ? null : <Text>Welcome</Text>}
</ View>
);
}
问题是,如果视图为假,则视图根本不会使用“欢迎”进行更新。虽然我的控制台日志给我错误。 到底是什么问题?
答案 0 :(得分:0)
尝试
constructor(props) {
super(props)
this.state={
isConditionFulfilled : false
}
}
componentDidMount(){
this.showView()
}
showView = async () => {
await this.setState({isConditionFulfilled : checkCondition()})
}
render() {
return (
<View>
{this.state.isConditionFulfilled ? <Text>Welcome</Text>: null}
</ View>
);
}
答案 1 :(得分:0)
showView
函数是一个异步函数,因此它返回一个promise。要正确使用它,您可以处理此承诺情况。例如:
class App extends React.Component {
showView = async () => {
let isConditionFulfilled = await checkCondition();
console.log('isConditionFulfilled', isConditionFulfilled)
return isConditionFulfilled;
}
render() {
let isConditionFulfilled;
this.showView().then( res => {
if (res) { isConditionFulfilled = true; }
isConditionFulfilled = false;
} )
return (
<div>
{
isConditionFulfilled ? <p>Foo</p> : null
}
</ div>
);
}
}
但是,这不是处理这种情况的好方法。使用生命周期方法来获取结果,然后将此值设置为您的状态。在渲染方法中,检查此状态值并有条件地渲染项目。这就是为什么我们有状态和生命周期方法的原因。
class App extends React.Component {
state = {
isConditionFulfilled: false,
}
componentDidMount() {
this.showView().then( res => this.setState({
isConditionFulfilled: res,
}))
}
showView = async () => {
let isConditionFulfilled = await checkCondition();
console.log('isConditionFulfilled', isConditionFulfilled)
return isConditionFulfilled;
}
render() {
return (
<div>
{
this.state.isConditionFulfilled ? <p>Foo</p> : null
}
</ div>
);
}
}