【问题标题】:How to pass key to root如何将密钥传递给root
【发布时间】:2020-10-26 00:15:23
【问题描述】:

我正在努力寻找一种方法将我的密钥传递给我的 return 语句的根 div

  const [recipes, setRecipes] = useState([]);
  const [search, setSearch] = useState("");
  const [query, setQuery] = useState("chicken");

  useEffect(() => {
      getRecipes();
    }, [query]);

  const getRecipes = async () => {
      const response = await fetch(`https://api.edamam.com/search?q=${query}&app_id=${App_ID}&app_key=${App_Key}`);
      const data = await response.json();
      setRecipes(data.hits);
      console.log(data.hits);
  }

  const updateSearch = e => {
    setSearch(e.target.value);
    console.log(search);
  };

  const getSearch = e => {
    e.preventDefault();
    setQuery(search);
    setSearch("")
  };


  return(
      <div className="App">
          <form onSubmit={getSearch} className="search-form">
           <input 
           className="search-bar" 
           type="text" value={search} 
           onChange={updateSearch}
           placeholder="Find a recipe" />
             <button className="search-button" type="submit">
             Search
             </button>
          </form>
          <div className="recipes">
          {recipes.map(recipe => (
            <Recipe
            title={recipe.recipe.label} 
            calories={Math.round(recipe.recipe.calories)}
            image={recipe.recipe.image}
            ingredients={recipe.recipe.ingredients}/>
            ))}
          </div>
      </div>
    );

当我只将密钥传递给 Recipe 组件时,我收到错误消息“列表中的每个子项都应该有一个唯一的“密钥”道具。”

我假设这意味着我需要将密钥传递给 className 为“App”的 div。如何在不将 map 函数传递给整个 return 语句的情况下做到这一点?

【问题讨论】:

  • 您不必将密钥传递给封闭的 div。您只需要为重复节点传递密钥,例如配方。只需确保每个项目都有一个唯一的密钥。
  • 你的意思是在 组件中?因为当我这样做时,我仍然得到错误
  • 我相信您可能将密钥添加到错误的位置。用代码示例查看我的答案。

标签: reactjs


【解决方案1】:

您不需要在封闭的 div 上使用密钥。您只需要重复节点上的键,并且应确保此键在所有项目中是唯一的。

数据条目通常具有 ID 字段。如果你有一个,而且它是独一无二的,你可能应该使用它作为密钥:

          {recipes.map(recipe => (
            <Recipe
              key={recipie.recipe.id}
              title={recipe.recipe.label} 
              calories={Math.round(recipe.recipe.calories)}
              image={recipe.recipe.image}
              ingredients={recipe.recipe.ingredients}
            />
          ))}

如果你不这样做,你可以依靠索引:

          {recipes.map((recipe, index) => (
            <Recipe
              key={index}
              title={recipe.recipe.label} 
              calories={Math.round(recipe.recipe.calories)}
              image={recipe.recipe.image}
              ingredients={recipe.recipe.ingredients}
            />
          ))}

将此选项用作最后的手段。如果项目的顺序发生变化,React 可能无法重用这些项目,这可能会影响性能。

注意:key 是一个特殊属性,React 使用它来了解哪些元素已更改以及需要如何更新它们。 React 管理 key 属性,你的组件实现不需要做任何事情。你只需要在创建许多相同的时候传递它。

您可以在此处阅读有关密钥的更多信息:https://reactjs.org/docs/lists-and-keys.html

【讨论】:

    猜你喜欢
    • 2017-12-16
    • 1970-01-01
    • 2022-01-13
    • 2021-11-15
    • 1970-01-01
    • 2012-01-23
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多