React.JS -处理空/未定义的情况,同时将JSON对象显示为键和值

我有以下代码,它执行嵌套JSON的所有键和值。它工作得很好,但只要任何键的值为null,代码就会在reduce函数处中断。我也想显示NULL值。我试图在else if中处理null和未定义的场景,但这不起作用。下面是我的代码,written.It必须是一个小的变化,我错过了。

  const myObj = {
      "key1": "value1",
      "key2": null,
      "key3": "value3",
      "key4": {
        "k1": "val1",
        "k2": {
          "p1": "v1",
          "p2": "v2",
          "p3": "v3"
        }
      }
    }


class Details extends React.component{
constructor(){
  this.getValues = this.getValues.bind(this);
}
getValues() {
     return (
        <div key={k} className="row">
            <div className="col-xs-6">{k}</div>
            <div className="col-xs-6">{v}</div>
        </div>
    )
    }

generateData(myObj) {

        const newData = Object.keys(myObj).reduce((result, currentKey) => {
          if (typeof myObj[currentKey] === 'string' || myObj[currentKey] instanceof String) {
            const elementToPush = getValues(currentKey, myObj[currentKey]);
            result.push(elementToPush);
          } else {
            const nested = generateData(myObj[currentKey]);
            result.push(...nested);
          }
          return result;
        }, []);
        return newData;
      }

render() {
    return (
        <div>
            <Header />
            <div className="content">
                {this.generateData(myObj)}
            </div>
        </div>
    )
}
}

转载请注明出处:http://www.hbbinz.com/article/20230526/2297813.html