我是钩子和反应的新手。我有以下代码:
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
,因为它需要它们。但这看起来不对劲或干净。
- 我通常如何用钩子处理它?我可以以某种方式将其全部放入一个班级吗?但是那我会再次达到正常状态,不是吗?我对这里的设置有些困惑。
如果将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);
}
}
这也将消除doSomething
功能中subs
的需求。