在我的 JSX 文件中,我有一个这样的函数。
async isPresent () {
const res = await AsyncFunction();
if (res) {
return true;
}
return false;
}
然后在条件渲染中使用它作为
{ this.isPresent() && <div> Content </div> }
但这总是返回 true。
我该如何解决?
最佳答案
你可以这样做:
const [isPresentResult, setIsPresentResult] = useState(false);
useEffect(() => {
this.isPresent().then(res => setIsPresentResult(res))
}, [])
// ...
{ isPresentResult && <div> Content </div> }
使用类组件:
class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = { isPresentResult: false };
}
componentWillMount = () => {
this.isPresent().then((isPresentResult) =>
this.setState({ isPresentResult }));
};
async isPresent() {
const res = await AsyncFunction();
return !!res;
}
render() {
return {this.state.isPresentResult && <div> Content </div>};
}
}
关于javascript - await 函数返回一个 promise,即使条件为 false 也返回 true | react 功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72343916/