In my JSX file, I have a function like this.
async isPresent () {
const res = await AsyncFunction();
if (res) {
return true;
}
return false;
}
and then using it in a conditional rendering as
{ this.isPresent() && <div> Content </div> }
But this always returns true.
How do I solve this?
You can do:
const [isPresentResult, setIsPresentResult] = useState(false);
useEffect(() => {
this.isPresent().then(res => setIsPresentResult(res))
}, [])
// ...
{ isPresentResult && <div> Content </div> }
Using Class Component:
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>};
}
}
You cannot have asynchronous logic in render. You need to extract the present
boolean into a state and make the asynchronous call inside something like componentDidMount
and then update the present
state from there.
Refer to the example below:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.