React:无法在对象中呈现值

React: Not able to render values in an Object

我有一个定义如下所示的组件。 creativeList 包含我有兴趣显示的值。它包含以下内容:

creativeList = [{keyID: "AC072", cost: 1461, people: 520, cpp: "2.81"}, 
{keyID: "AC098", cost: 1600, people: 470, cpp: "3.4"}]

我希望能够通过 return 在我的组件中显示 keyID。我可以通过登录到控制台来获取值,但是,我无法 return 它。有人可以帮我吗?

function DisplayList(props) {
    const creativeList = props.creativeList

    function ret(){
        creativeList.forEach(function(item){
            const i = item[0]

            console.log(i.keyID)

            return (
                <li>{i.keyID}</li>
            );
        })
    }

    return (
        <div>
            <li>List:</li>
            {ret()}
        </div>
    );
}

export default DisplayList;

Add a return statement just before forEach statement and replace forEach by map

map returns 回调参数返回的元素数组,与 forEach 不同。

forEach returns 未定义,这就是您的列表未打印的原因。

function ret(){
        return creativeList.map(function(item){

            console.log(item.keyID)

            return (
                <li>{item.keyID}</li>
            );
        })
    }

试试这个。您错过了 return 一个组件,当然您应该使用 map 而不是 foreach

import React from "react";

function DisplayList(props) {
  const creativeList = props.creativeList;


  function ret() {
    return creativeList.map(function(item) {
      const i = item;

      console.log(i.keyID);

      return <li>{i.keyID}</li>;
    });
  }

  return (
    <div>
      <li>List:</li>
      {ret()}
    </div>
  );
}

export default DisplayList;

没有办法停止forEach,如果你想做return,forEach returns undefined,用map代替。 工作示例:sandbox

您可以使用 map 进行简化。还要将 key 属性添加到列表中的每个元素。

function DisplayList(props) {
  const { creativeList = [] } = props.creativeList;
  return (
    <div>
      <div>List:</div>
      {creativeList.map(({ keyID }) => (
        <li key={keyID}>{keyID}</li>
      ))}
    </div>
  );
}
export default DisplayList;