[英]Promise, async, await - Boolean returns false but if condition still gets called
[英]await function returns a promise and returns true even if the condition is false | React Functional Component
在我的 JSX 文件中,我有一个这样的 function。
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 组件:
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>};
}
}
渲染中不能有异步逻辑。 您需要将present
的 boolean 提取到 state 中,并在类似componentDidMount
的内部进行异步调用,然后从那里更新present
的 state。
请参考以下示例:
const sleep = (delay) => new Promise(res => setTimeout(() => res(true), delay)) class App extends React.Component { constructor() { super(); this.state = { present: false, }; } componentDidMount() { sleep(1000).then((res) => { if (res) { this.setState({ present: true }); } }); } render() { return <div>{this.state.present? "Present": "Not Present"}</div>; } } ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.