javascript - React map 函数混淆

标签 javascript reactjs dictionary

在 React 组件中使用 map 函数时,我有点困惑。我有一个食谱组件,它从 App 组件获取食谱数据。

应用组件

<Recipes recipes={recipes} />

食谱组件

export default class Recipes extends Component {
  // THIS FUNCTION IS RETURNING NOTHING
  renderRecipes() {
    return this.props.recipes.map((recipe) => {
      <h1>{recipe.name}</h1>
    });
  }
  render() {
    let recipe = this.props.recipes.map((recipe) => {
      return (
        <h1>{recipe.name}</h1>
      );
    });
    return(
      <div>
        // CALLING THE FUNCTION HERE DOES NOT WORK
        { this.renderRecipes() }
        // HOWEVER CALLING THE VARIABLE DOES WORK
        { recipe }
      </div>
    );
  }
}

这就是我感到困惑的地方。创建执行 map 函数的函数不返回任何内容,但是移动 map 函数并将输出分配给 render 内的 recipe 变量() 工作正常。为什么 renderRecipes 中的 map 函数不返回任何内容?

最佳答案

因为您没有在 map 体内返回任何东西,所以可以这样使用它:

renderRecipes() {
    return this.props.recipes.map((recipe, i) => {
        return <h1 key={i}> {recipe.name} </h1>
    });
}

或删除 {}:

renderRecipes() {
    return this.props.recipes.map((recipe, i) => <h1 key={i}> {recipe.name} </h1> );
}

When {} is required with map?

当您想根据某些条件进行一些计算或返回不同的元素时,请使用 {} 创建一个范围来定义一些变量并使用 if 条件,但在这里您只是想要返回单个元素,因此此处不需要 {}

注意:您需要为每个元素分配唯一的key,这里我使用了索引,但我建议您使用配方对象的任何唯一属性。

关于javascript - React map 函数混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44104784/

相关文章:

c++ - std::map 的 const_cast 问题

C# HtmlEncode,然后使用 .innerHTML Javascript 插入

javascript - 如何导入文件以及如何在需要的地方调用它

javascript - 将 Create-react-app 与 googleapis 一起使用时出错

javascript - 使用 createRef 的焦点子组件不起作用

python - 如何从字符串中删除字典中对应的单词?

python - 展平嵌套字典 - 将列表元素转换为字符串

javascript - 如何在 JS 中单击省略号时在模式中显示整个文本?

javascript - 如何在 react 中为两个或多个事件添加一个事件监听器

javascript - 在 chrome 扩展程序中显示警报对话框