首页 > 解决方案 > React 对象条目不呈现任何内容

问题描述

所以我有这个代码:

class LatestRecipes extends Component
{
  render()
  {
     return(
      <div>
        <ul>
        {
          Object.entries(this.props.latestRecipes).forEach(([key, recipe]) => 
            <li key={key}>
              <div key={key}>
                <Link to={{pathname: '/recipe/' + recipe.Name, state: { recipe: recipe, key: key }}}>{recipe.Name}</Link>    
              </div>
            </li>
        )}
        </ul>
      </div>
    );
   }
}

但是我的 React App 没有渲染任何li元素。

这是我this.props.latestRecipes现在的情况:

-LOyADRLntFBWyj1TtGx: {Description: "Description", Ingredients: Array(1), Name: "Name"}
-LOyBKQJcAsR0YfHAjrZ: {Description: "Description", Ingredients: Array(1), Name: "Name"}

我想要的是能够发送key(-LOyADRLntFBWyj1TtGx)和recipe配方组件。并在li元素中渲染配方详细信息

没有错误,没有任何东西,如果我控制台记录它,我会得到我正在寻找的确切结果。

标签: reactjs

解决方案


你需要 amap而不是 a forEach

Array.forEach函数不返回元素数组(它undefined根据MDN 文档返回),因为它根据map被映射数组的元素返回一个新数组。

例如:

const timesTwo = [1, 2, 3].map(e => e * 2);
console.log(timesTwo); // output: [2, 4, 6]

同样不适用于forEach. 你必须这样做:

const timesTwo = [];
[1, 2, 3].forEach(e => {
  timesTwo.push(e * 2);
});
console.log(timesTwo); // output: [2, 4, 6]

推荐阅读