【问题标题】:Building a reusable component to map through different sets of data React构建一个可重用的组件来映射不同的数据集 React
【发布时间】:2022-01-14 22:05:25
【问题描述】:

正如标题所说,我正在传递 pokemon 数据和 rickandmorty 数据。我也碰巧使用顺风选择菜单来做出相当长的反应。有没有比有条件地映射数据更好的方法呢?我知道我可以做到这一点

{pokemons ? (
            {pokemons?.map((pokemon, idx) => (
              **30 line long code for the select menu**
            ))}
         
        ) : (
            {rickAndMorty?.map((character, idx) => (
              **Another 30 long line code for the select menu**
            ))}
        )}

这是唯一的方法还是有更清洁的方法?任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 这两个地方的30行长代码是一样的吗?如果不同,有何不同?
  • 代码相同,但 props 和嵌套键不同。对于 pokemon,我只需要使用 {pokemon} 来显示 pokemon 的名称,但对于 rick and morty,我必须使用 {character.name} 来显示 rick and morty 的名称。

标签: javascript reactjs conditional-statements conditional-operator


【解决方案1】:

我建议尝试将任何重复的代码分离到一些通用组件中,例如:

const GenericSelectItem = (props)=>{
    return (<>{/* props.itemValues */}</>);
};

const GenericSelectList = (props)=>{
    const { selectItems } = props;
    return (<SelectList>
        { selectItems.map( selectItem => <GenericSelectItem selectItem={ selectItem } /> ) }
    </SelectList>);
};

const Example = (props)=>{
    const itemsToDisplay = pokemons || rickAndMorty;
    return (<>
        { !itemsToDisplay ? null : <GenericSelectList selectItems={ itemsToDisplay } /> }
    </>);
};

如果 SelectItem 非常不同,请添加特定组件,例如:

const PokemonItem = (props)=>{
    return (<GenericSelectItem>{/* pokemon specific variations */}</GenericSelectItem>);
};

const RickAndMortyItem = (props)=>{
    return (<GenericSelectItem>{/* rickAndMorty specific variations */}</GenericSelectItem>);
};

【讨论】:

    猜你喜欢
    • 2021-05-29
    • 2021-12-13
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多