在 ReactJs 中渲染对象数组

IT技术 javascript reactjs babeljs
2021-05-11 22:08:52

我正在尝试查看对象属性(此示例的名称)并在函数中的简单循环中列出它们。我发现了一些非常尴尬的方法,但似乎不对。

这是我得到的:

const ItemsToSell = [{"Name":"Cup","Price":"99.99"},{"Name":"IPhone","Price":"99.99"},{
"Name":"Pen","Price":"99.99"}]

function ListItem(props) {
  return <li>{props.value}</li>;
}

function NumberList(props) {
  const a = props.numbers;
  return (
    <ul>
      {a.map((number) =>
        <ListItem  value={ItemsToSell[number].Name} />
      )}
    </ul>
  );
}

const numbers = [0,1, 2];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

有一个更好的方法吗?我只需要一个循环来遍历对象数组,列出所需的属性并创建许多 html 节点之一。

2个回答

您可以简单地映射ItemsToSell数组

const ItemsToSell = [{"Name":"Cup","Price":"99.99"},{"Name":"IPhone","Price":"99.99"},{
"Name":"Pen","Price":"99.99"}]

function ListItem(props) {
  return <li>{props.value}</li>;
}

function NumberList(props) {
  return (
    <ul>
      {ItemsToSell.map((obj, index) =>
        <ListItem  key={index} value={obj.Name} />
      )}
    </ul>
  );
}

ReactDOM.render(
  <NumberList  />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

为什么不遍历ItemsToSell数组?您不必再添加一个。

注意key在循环元素时包含属性,否则您将收到错误消息。

const ItemsToSell = [{"Name":"Cup","Price":"99.99"},{"Name":"IPhone","Price":"99.99"},{
"Name":"Pen","Price":"99.99"}]

function ListItem(props) {
  return <li>{props.value}</li>;
}

function NumberList(props) {
  return (
    <ul>
      {ItemsToSell.map((elem, index) =>
        <ListItem value={elem.Name} key={index} />
      )}
    </ul>
  );
}

ReactDOM.render(
  <NumberList />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>