在这种情况下如何避免重复代码?

时间:2021-05-20 16:56:28

标签: reactjs

我写了这段代码。根据是否包含在另一个数组中的项目返回true或false值。

但是我的前辈说这段代码不干。我想不出办法让它更干燥。有人可以帮我看看方法

Array.prototype.filter

这两个返回值之间的唯一区别是 const renderItem = ({item, index}) => { if (favList.includes(item.id)) { return ( <IndividualProduct info={item} index={index} key={index} fav={true} stateChange={stateChange} setLoading={setLoading} setSignInShown={setSignInShown} /> ); } else { return ( <IndividualProduct info={item} index={index} key={index} fav={false} stateChange={stateChange} setLoading={setLoading} setSignInShown={setSignInShown} /> ); } }; 属性的 true 或 false 值

1 个答案:

答案 0 :(得分:6)

唯一改变的是 fav 属性,因此请改用 .includes 调用的结果。

const renderItem = ({ item, index }) => (
    <IndividualProduct
        info={item}
        index={index}
        key={index}
        fav={favList.includes(item.id)}
        stateChange={stateChange}
        setLoading={setLoading}
        setSignInShown={setSignInShown}
    />
);

另一种选择是传播与道具同名的变量名。

const renderItem = ({ item, index }) => (
    <IndividualProduct
        {...{ index, stateChange, setLoading, setSignInShown }}
        info={item}
        key={index}
        fav={favList.includes(item.id)}
    />
);