我是钩子和React的新手。我有以下代码:
import React, { useState, useRef } from 'react';
let doSomething = (obj, section, setActiveItem, subs, i) => {
if (
obj.previousPosition === 'in' &&
obj.currentPosition === 'below'
) {
if (i !== 0) {
setActiveItem(subs[i - 1].id);
}
}
};
export default ({ data }) => {
const subs = [
{
label: 'Section 1',
id: 'section1',
ref: useRef(null),
},
{
label: 'Section 2',
id: 'section2',
ref: useRef(null),
},
];
const [activeItem, setActiveItem] = useState('section1');
return (
<>
{subs.map((sub, i) => {
return (
<Waypoint
key={sub.id}
bottomOffset="75%"
onEnter={obj => {
doSomething(obj, sub.id, setActiveItem, subs, i);
//I DONT LIKE THAT I NEED TO PASS ON EVERYTHING HERE
}}
>
<Section id={sub.id} ref={sub.ref} />
</Waypoint>
);
})}
</>
);
};
现在,我的问题是在我的onEnter
函数中,我需要将所有这些属性传递给函数doSomething
,因为它需要它们。但这似乎不正确或不正确。
答案 0 :(得分:0)
如果将doSomething
放入组件,则至少可以删除传递给它的五个参数中的两个:
const component = ({ data }) => {
const subs = [];
const [activeItem, setActiveItem] = useState('section1');
const doSomething = (obj, section, i) => {
/* ... */
setActiveItem(subs[i - 1].id);
}
return (
{ /* ... */ }
<Waypoint onEnter={(obj) => doSomething(obj, sub.id, i)} { ... } />
{ /* ... */ }
);
}
根据您的代码,您还可以删除sub.id
,因为您当前未在函数中使用它。
但是我建议从参数中删除i
并使用section
参数,而不要检查是否i !== 0
并从subs
数组中获取对象:>
// Without `i`
doSomething = (obj, section) => {
if (
obj.previousPosition === 'in' &&
obj.currentPosition === 'below'
) {
// The if is not needed anymore.
setActiveItem(section);
}
}
这还将消除subs
函数中对doSomething
的需求。