简体   繁体   English

await function 返回一个 promise 并且即使条件为假也返回 true | 反应功能组件

[英]await function returns a promise and returns true even if the condition is false | React Functional Component

In my JSX file, I have a function like this.在我的 JSX 文件中,我有一个这样的 function。

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.但这总是返回 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 组件:

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.您需要将present的 boolean 提取到 state 中,并在类似componentDidMount的内部进行异步调用,然后从那里更新present的 state。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM