如何解决 React 中的“逗号运算符左侧未使用且没有副作用.ts(2695)”错误?

Inn*_*ode 11 javascript typescript reactjs

import React from "react";
import { useRecoilState } from "recoil";
import { Industry, industryState } from "../atoms/industriesAtoms";

const useIndustryData = () => {
  const [industryStateValue, setIndustryStateValue] =
  useRecoilState(industryState);

  const onJoinOrLeaveIndustry = (industryData: Industry, isJoined: boolean) => {
    // is the user signed in
    // if not => open auth modal

    if (isJoined) {
      leaveIndustry(industryData.id);
      return;
    }
    joinIndustry(industryData);
    // onJoinOrLeaveIndustry;
  };

  const joinIndustry = (industryData: Industry) => {};

  const leaveIndustry = (industryId: string) => {};

  return (

  // data and functions,
  *industryStateValue,* onJoinOrLeaveIndustry
 );

};
export default useIndustryData;
Run Code Online (Sandbox Code Playgroud)

我正在一个 React 项目中处理上面的代码,并且在屏幕截图的第 27 行中收到一个错误,即逗号运算符的左侧未使用且没有副作用.ts(2695)。

我想了解为什么会出现此错误,以及如何解决它。

我在这里发现了类似的问题,但该解决方案对我自己的情况没有帮助。逗号运算符的左侧未使用...

T.J*_*der 11

这段代码:

return (
    // data and functions,
    industryStateValue, onJoinOrLeaveIndustry
);
Run Code Online (Sandbox Code Playgroud)

等价于:

return (
    // data and functions,
    onJoinOrLeaveIndustry
);
Run Code Online (Sandbox Code Playgroud)

...因为industryStateValue是一个简单变量,因此评估它没有副作用。逗号运算符计算其左侧操作数,丢弃该值,计算其右侧操作数,然后将该值作为结果。

如果您打算返回这两个值,则必须将它们包装在某些东西中。当只有两三个这样的情况时,通常将它们包装在一个数组中:

return [ // <===
    // data and functions,
    industryStateValue, onJoinOrLeaveIndustry
];       // <===
Run Code Online (Sandbox Code Playgroud)

然后使用钩子的代码可以解构为离散变量,就像使用useStateor一样useRecoilState

const [state, handler] = useIndustryData();
Run Code Online (Sandbox Code Playgroud)

如果您愿意,可以使用对象代替数组,方法是使用{}以下命令[]

return { // <===
    // data and functions,
    industryStateValue, onJoinOrLeaveIndustry
};       // <===
Run Code Online (Sandbox Code Playgroud)

然后使用它的代码将使用对象解构({}而不是[]):

const { industryStateValue, onJoinOrLeaveIndustry } = useIndustryData();
Run Code Online (Sandbox Code Playgroud)

对于少量值(例如三个或更少),通常的做法是使用像useStateand useRecoilStatedo 这样的数组,因为调用者更容易控制它们解构成的变量的名称。但对于四个或更多值,一个对象会更清晰,因为当你进入这么多值时,位置解构可能很难遵循。以下是调用者在解构对象时如何使用不同的名称(state如数组示例中所示):handler

const { industryStateValue: state, onJoinOrLeaveIndustry: handler } = useIndustryData();
Run Code Online (Sandbox Code Playgroud)