【问题标题】:How to render component using boolean state values in redux in react?如何在反应中使用redux中的布尔状态值渲染组件?
【发布时间】:2021-09-23 03:19:27
【问题描述】:

我正在开发一个 react 应用程序,我在 redux 商店中有 3 个布尔变量,我想在 3 个组件之间切换以使用这些布尔值进行渲染。我该怎么做?

这是我的代码:

<Grid>
    <Grid.Row>
        <Grid.Column width={1} />
        <Grid.Column width={14}>
            this.props.openCreateForm?<Form/>:</>
            this.props.openViewPopup?<ViewPopup/>:</>
            this.props.openCredsPopup?<CredsPopup/>:</>
        </Grid.Column>             
        <Grid.Column width={1} />
    </Grid.Row>
</Grid>

Grid.Column里面我只想渲染这三个组件中的一个。所有的布尔值都来自redux状态。

Error

react-dom.development.js:24036 Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

我该怎么做?我收到一个错误

谢谢

【问题讨论】:

  • 你遇到了什么错误?
  • 如何从 redux 中获取状态?挂钩还是连接组件?
  • 我正在使用mapStatetoProps 获取值
  • 应该是这样的{this.props.openCreateForm?&lt;Form/&gt;:&lt;/&gt;}。这是一个错字吗?
  • 当您使用JSX syntax 时,编译器将要求将嵌入的JavaScript 代码封装在{ }

标签: javascript html reactjs redux react-redux


【解决方案1】:
const { openCreateForm, openViewPopup, openCredsPopup } = this.props

        <Grid>
        <Grid.Row>
            <Grid.Column width={1} />
            <Grid.Column width={14}>
                {openCreateForm && <Form/>}
                {openViewPopup && <ViewPopup/>}
                {openCredsPopup && <CredsPopup/>}
            </Grid.Column>             
            <Grid.Column width={1} />
        </Grid.Row>
    </Grid>

使用解构获取 props 值并使用 && 运算符进行条件渲染。它之所以有效,是因为在 JavaScript 中,真 && 表达式总是计算为表达式,而假 && 表达式总是计算为假。

参考这里:https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator

【讨论】:

    【解决方案2】:

    您需要将它们包含在 { }

    const { openCreateForm, openViewPopup, openCredsPopup } = this.props
    
               <Grid.Column width={14}>
                 { openCreateForm ? <Form/> : 
                   openViewPopup ? <ViewPopup/> :
                   openCredsPopup ? <CredsPopup/> : </> }
               </Grid.Column>
    

    或者如果你不想嵌套三元,

               <Grid.Column width={14}>
                 { this.props.openCreateForm && <Form/> ||
                   this.props.openViewPopup && <ViewPopup/> ||
                   this.props.openCredsPopup && <CredsPopup/> || </> }
               </Grid.Column>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多