在React中传递函数和钩子?还是将它们放在一起?

时间:2019-05-14 09:16:02

标签: javascript reactjs react-hooks

我是钩子和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,因为它需要它们。但这似乎不正确或不正确。

  • 我通常如何用钩子处理?我能以某种方式将其全部归类吗?但是然后我又会恢复正常状态,不是吗?我对这里的设置有些困惑。

1 个答案:

答案 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的需求。