【问题标题】:Conditional rendering question with ReactJSReactJS 的条件渲染问题
【发布时间】:2018-12-02 17:54:39
【问题描述】:

我正在尝试在 React 中使用 <Conditional if={condition}> 组件,该组件仅在条件为真时才呈现其内容。

我使用了来自 here 的代码,正如 Broda Noel 对 this question 的回复中所述。您还可以看到代码here。

import * as React from 'react';

const Conditional = props => (
    !!props.if && props.children
);

class Item extends React.Component {
    render() {
        const item = { id: 2 };

        return (
            <>
                <h2>Item detail</h2>
                {/* Display item.foo.name if `foo` property exists */}
                <Conditional if={item.foo}>
                    {item.foo.name}
                </Conditional>
            </>);
    }
}

export default Item;

失败并出现错误:

Uncaught TypeError: Cannot read property 'name' of undefined

我知道我也可以使用{item.foo &amp;&amp; item.foo.name},但是当代码变得更复杂时,我发现Conditional 的使用更具可读性。最重要的是,我真的很想了解这里发生了什么。

为什么 React 会渲染 Conditional 的内容,即使是条件为假? 有没有办法更改条件组件以使其在这种情况下工作?

我正在使用带有 typescript 的 React 16.4.1。

【问题讨论】:

  • 尝试将if设置为if={item.foo !== undefined} 。你的 if 没有条件、比较或类似的东西。

标签: reactjs typescript


【解决方案1】:

代码:

<Conditional if={item.foo}>
  {item.foo.name}
</Conditional>

转译为:

React.createElement(Condition, { if: item.foo }, item.foo.name)

所以即使条件为假,它也会尝试访问属性name。

当代码变得更复杂时,我建议你使用下面的代码:

import * as React from 'react';

class Item extends React.Component {
  renderConditional (item) {
    if (!item.foo) {
      return null;
    }
    return item.foo.name; // Or some jsx
  }

  render() {
    const item = { id: 2 };

    return (
      <>
        <h2>Item detail</h2>
        {this.renderConditional(item)}
      </>
    );
  }
}

export default Item;

您还可以创建另一个组件来呈现数据并检查新组件内的对象。

【讨论】:

    【解决方案2】:

    问题是您的组件&lt;Conditional&gt; 在if 属性中没有逻辑表达式。执行此操作的“反应方式”是按原样使用条件渲染:

    render() {
        const item = { id: 2 };
    
        return (
          <>
            <h2>Item detail</h2>
            { item.foo !== undefined &&  // React Way to Conditional Rendering
              {item.foo.name}
            }
          </>
        );
    }
    

    我建议您阅读Conditional Rendering 的文档

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 2012-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多