【问题标题】:Replacing true/false/null in React Map render with strings "true/false/null"用字符串“true/false/null”替换 React Map 渲染中的 true/false/null
【发布时间】:2020-12-05 20:17:22
【问题描述】:

假设在 React 中,我正在迭代返回状态为 this.state.searchData 的 JSON 数据,并且返回的一些值包含来自 api 调用的 true 或 false 或 null,例如:

   "active": true,
   "partition": null,
   "auth": false

对于下面的地图迭代,我将如何测试键/值中的每个值,然后用字符串“true”或“false”或“null”替换它们以显示在浏览器的渲染中?现在我的代码正确呈现所有内容,直到它在键的值中遇到真、假或空,它只呈现任何内容/空

{Object.entries(this.state.searchData).map(([key, value]) => (
  <ul>
    *** test key value here for null, false or true and output string "null, false or true"
    <li>{key} : {value}</li>
  </ul>
   )
  )
}

【问题讨论】:

    标签: javascript node.js reactjs ecmascript-6


    【解决方案1】:

    使用Array.reduce

    let data = {
      "active": true,
      "partition": null,
      "auth": false,
      "Valued": "MyValue"
    };
    
    let asTextData = Object.entries(data).reduce((result, [key, value]) => {
      let item = {}
      switch (value) {
        case null:
          item[key]="null";
          return {...result,...item}
        case true:
          item[key]="true";
          return {...result,...item} 
        case false:
          item[key]="false";
          return {...result,...item}
        default :
          item[key]=value;
          return {...result,...item}
      }
    },{});
    
    console.log(asTextData);
    您也可以使用String() 进行转换,但如果您在渲染时使用它并且您有其他值类型,如整数或浮点数,您可能需要再次将它们转换为数字。

    【讨论】:

      【解决方案2】:

      在 React/JSX 模板中,布尔值/空值/未定义值不会渲染,因为它们也用于条件渲染。

      参考: https://reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored

      但是你可以转换成字符串并渲染它?

      <h1>{String(true)}</h1>
      <h2>{String(false)}</h2>
      <h2>{String(null)}</h2>
      

      以上所有内容都将呈现为字符串。

      【讨论】:

        【解决方案3】:

        使用String对象获取字符串表示 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

        <li>{key} : {String(value)}</li>
        

        【讨论】:

          猜你喜欢
          • 2016-03-27
          • 2015-02-22
          • 2011-06-13
          • 1970-01-01
          • 1970-01-01
          • 2020-12-15
          • 1970-01-01
          • 2021-09-27
          • 2011-01-31
          相关资源
          最近更新 更多