基于状态的React条件渲染 [英] Conditional rendering in React based on state

查看:44
本文介绍了基于状态的React条件渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在发送一个API请求,并将其结果呈现到UI中.

I'm sending an API request and render its result in to UI.

现在,对于错误处理,我希望如果发生错误,则将包含错误消息的div呈现到UI中.

Now, for the error-handling, I wanted that if there is an error a div which contains an error message gets rendered in to the UI.

为此,我编写了以下三元条件:

To achieve this I wrote the following ternary condition:

const showError = this.state.error
? `<div className="error-container">
    Error:
      <p>{this.state.error}</p>
   </div>`
: '';

然后在我的渲染方法中使用它: {showError}

And then used this inside my render method: {showError}

但是React将结果视为字符串,并将以下内容呈现到UI:

But React see the result as a string and renders the following to the UI:

我在做什么错了?

推荐答案

问题是,您通过将内容包装在``{backticks)中,使 showError 成为字符串,并且不再保留JSX表达式

Problem is that you made showError a string by wrapping the content within ``(backticks) and it no longer remains a JSX expression

改为使用().另外,当您不想返回任何内容时,应返回 null 而不是空字符串

Use () instead. Also when you don't want to return anything, you should return null instead of an empty string

const showError = this.state.error
? (<div className="error-container">
    Error:
      <p>{this.state.error}</p>
   </div>)
: '';

这篇关于基于状态的React条件渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆