繁体   English   中英

React 使用 map 迭代嵌套数组/对象。 渲染每个地图功能是否必须返回?

[英]React iterate nested arrays/objects with map. Is return mandatory to render each map function?

我是 React 的新手。 我正在构建一个小的功能组件来呈现 Pokemon 的弱点。

它将存储在状态 (pokemonState.types) 中的 Pokemon 类型作为每个类型的对象数组,将类型与包含所有类型有效性的 JSON 文件进行比较(见下文)。

types_data.json

  "electric": {
"attack": {
  "double": ["flying", "water"],
  "half": ["dragon", "electric", "grass"],
  "zero": ["ground"]
},
"defense": {
  "half": ["electric", "flying", "steel"],
  "double": ["ground"],
  "zero": []
}

为了获得我想要的数据,我需要进行多次迭代,我注意到我的组件仅在我指定 return 关键字并将我的元素包装在 HTML 标记中时才会呈现。

不呈现任何内容的函数(但 console.log 不返回 undefined)

  const pokemonTypeChart = () => {
if (!_.isEmpty(pokemonState)) {
  const allTypes = Object.entries(types_data);
  const typeEffectiveness = allTypes.map(([key, value]) => {
    pokemonState.types.map((el) => {
      if (el.type.name === key) {
        console.log(key, value);
        return <p>{el}</p>;
      }
    });
  });
  return (
    <div>
      <h1>Test</h1>
      <p>{typeEffectiveness}</p>
    </div>
  );
}};

运行良好的功能:

const pokemonTypeChart = () => {
if (!_.isEmpty(pokemonState)) {
  const allTypes = Object.entries(types_data);
  return (
    <div>
      <h1>Type Effectiveness</h1>
      {allTypes.map(([key, value]) => {
        return (
          <>
            {pokemonState.types.map((el, i) => {
              if (el.type.name === key)
                return <h3 key={i}>{value.defense.double}</h3>;
            })}
          </>
        );
      })}
    </div>
  );
}};

我的问题是:

  • 对于不渲染任何东西的函数,问题是每次迭代后我都不使用 return 对吗?
  • 在这种情况下,我的第二个功能是好的做法吗? 有没有更干净的方式我应该写它?

谢谢你的帮助。

您的第一个函数不起作用的原因是您正在返回<p>{el}</p>

el等于一个对象 & 你期待一个字符串。

具体来说,在这种情况下,它类似于{type:{name: "electric"}

如果你从return <p>{el}</p>; return <p>{el.type.name}</p>; ,然后修复我们内部的.map ,所以你越来越近了。

但是,您还有第二个问题……外部.map函数没有返回任何内容。 您的typeEffectiveness变量是我们最终要渲染的变量,该变量等于调用allTypes.map的结果。 当您嵌套的pokemonState.types.map函数返回给父.map函数时,您的父.map函数没有 return 语句。

最终,您正在渲染{typeEffectiveness} ,因此我们必须确保该变量是一个将渲染到 DOM 的 react 元素数组。

还有一些其他的小问题。 也就是说,我们必须在这里删除段落标签<p>{typeEffectiveness}</p>否则我们最终会得到嵌套的p标签,因为typeEffectiveness列表中的每个项目都已经包含在<p></p>

最后,您还应该将关键标签添加到您的列表项中。 <p key="{el.type.name}">{el.type.name}</p>

在此处深入了解列表和键的文档: https : //reactjs.org/docs/lists-and-keys.html

以下代码是您的第一个函数的调试版本。

我还在下面包含了您的部分功能的重构版本。 当我们真的只关心我们的pokemonState存在的类型时,映射整个types_data对象条目将是相当低效的,所以看看我在下面的方法。

 const e = React.createElement; const pokemonState ={types: [{type:{name: "electric"}}]}; let types_data = { "electric": { "attack": { "double": ["flying", "water"], "half": ["dragon", "electric", "grass"], "zero": ["ground"] }, "defense": { "half": ["electric", "flying", "steel"], "double": ["ground"], "zero": [] } } }; const PokemonTypeChart = () => { if (!_.isEmpty(pokemonState)) { const allTypes = Object.entries(types_data); const typeEffectiveness = allTypes.map(([key, value]) => { return (pokemonState.types.map((el) => { if (el.type.name === key) { return ( <p key="{el.type.name}">{el.type.name}</p> ); } })); }); return ( <div> <h1>Test</h1> {typeEffectiveness} </div> ); }}; const domContainer = document.querySelector('#pokemon'); ReactDOM.render(e(PokemonTypeChart), domContainer);
 <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/underscore@1.13.1/underscore-umd-min.js"></script> <div id="pokemon"></div>

 const e = React.createElement; const pokemonState ={types: [{type:{name: "electric"}}]}; let types_data = { "electric": { "attack": { "double": ["flying", "water"], "half": ["dragon", "electric", "grass"], "zero": ["ground"] }, "defense": { "half": ["electric", "flying", "steel"], "double": ["ground"], "zero": [] } } }; const PokemonChart = () => { if (!_.isEmpty(pokemonState)) { const plistItems = pokemonState.types.map((item) => types_data[item.type.name].defense.double.map((i) => <p key={i}>{i}</p> )); return ( <div> <h1>Type Effectiveness</h1> {plistItems} </div> ); }}; const domContainer = document.querySelector('#pokemon'); ReactDOM.render(e(PokemonChart), domContainer);
 <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/underscore@1.13.1/underscore-umd-min.js"></script> <div id="pokemon"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM