簡體   English   中英

await function 返回一個 promise 並且即使條件為假也返回 true | 反應功能組件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM