简体   繁体   English

如何在反应js中处理map JSON数据?

[英]How to map JSON data in react js?

I want to map JSON data in key-value manner.我想以键值方式获取 map JSON 数据。 I tried it doing on stackblitz but it is showing error.我试过在 stackblitz 上做,但它显示错误。

THE CODE I WROTE:我写的代码:

import React from "react";
import ReactDOM from "react-dom";

const sampleJSON = {
  name: "Pluralsight",
  number: 1,
  address: "India",
  website: "https://www.pluralsight.com/"
};

function App() {
  return (
    <div>
      {Object.keys(sampleJSON).map((key, i) => (
        <p key={i}>
          <span>Key Name: {key}</span>
          <span>Value: {sampleJSON[key]}</span>
        </p>
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("app"));

THE ERROR I AM GETTING IS:我得到的错误是:

Error in /turbo_modules/react-dom@17.0.0/cjs/react-dom.development.js (26083:13) Target container is not a DOM element. /turbo_modules/react-dom@17.0.0/cjs/react-dom.development.js 中的错误 (26083:13) 目标容器不是 DOM 元素。

https://stackblitz.com/edit/react-lyrp91 https://stackblitz.com/edit/react-lyrp91

You must export default react components.您必须导出默认的反应组件。 I got it working in a sandbox ( link ), by changing this line通过更改此行,我让它在沙箱(链接)中工作

ReactDOM.render(<App />, document.getElementById("app"));

to this对此

export default App;

You need to export your app component instead of rendering it to the element id app.您需要导出您的app component ,而不是将其渲染到元素 ID 应用程序。 The problem is it tries to find element id app , but it can't find in the DOM.问题是它试图找到元素 id app ,但在 DOM 中找不到。 However index.js do the same thing, so you don't have to do the ReactDOM.render thing.然而index.js做同样的事情,所以你不必做ReactDOM.render的事情。

ReactDOM.render(<App />, document.getElementById("root")); // you will find this line in index.js, you don't need to do this in app.js // 你会在 index.js 中找到这一行,你不需要在 app.js 中这样做

Stackblitz Link Stackblitz 链接

import React from "react";

const sampleJSON = {
  name: "Pluralsight",
  number: 1,
  address: "India",
  website: "https://www.pluralsight.com/"
};

export default function App() {
  return (
    <div>
      {Object.keys(sampleJSON).map((key, i) => (
        <p key={i}>
          <span>Key Name: {key}</span>
          <span>Value: {sampleJSON[key]}</span>
        </p>
      ))}
    </div>
  );
}

You have set state and then in render function add "map" and return html.您已设置 state,然后在渲染 function 添加“地图”并返回 html。

  render()
  {
   
    return(
     <div className='training'>
          <div className='items'>
            {
              this.state.training.map( (row,index)=>{
                 return(
                    <h1>{index}</h1>    
                 )                 
              }) 
            }             
          </div>
     </div>
    )
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM