【问题标题】:Passing down functions and hooks in React? Or keeping it all together?在 React 中传递函数和钩子?还是把它们放在一起?
【发布时间】:2019-05-14 09:16:01
【问题描述】:

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

  • 我通常如何用钩子处理这个问题?我可以以某种方式将它们全部归为一类吗?但是那样我会再次恢复正常状态,不是吗?我对这里的设置有点困惑。

【问题讨论】:

  • 你需要doSomething 在组件之外吗?
  • 不,不是。但我不明白使用钩子在组件内部使用doSomething 的代码会是什么样子。 : /

标签: javascript reactjs react-hooks


【解决方案1】:

如果您将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);
    }
}

这也将消除 subsdoSomething 函数中的需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2016-11-23
    • 2017-11-24
    相关资源
    最近更新 更多