我如何在反应钩子中动态调用方法

how can i call method dynamically in react hooks

在我的 React 钩子中,我定义了两个用于设置变量的函数: setProjectMiddleCodesetProjectToolCode.

我希望在我的react hooks中调用这两个方法来避免重复代码。

我想这样做:

//variable define
let data;
let index = res.data.indexOf(res.code.value);

//call dynamic

if(some state ==='A'){
 data= "setProjectMiddleCode"
}else{
 data = "setProjectToolCode"
}

if (index < 0) {
  this[data](res.data.concat(res.code.value));
} else {
  this[data](res.data.filter((_, i) => i !== index));
}

我当前的代码:

  const [projectMiddleCode, setProjectMiddleCode] = useState([]);
  const [projectToolCode, setProjectToolCode] = useState([]);

const ProjectWrite = memo(({}) => {
  let component;
  const dispatch = useDispatch();

  const [projectMiddleCode, setProjectMiddleCode] = useState([]);
  const [projectToolCode, setProjectToolCode] = useState([]);

  const callbackFromChild = useCallback(
    res => () => {
        let index = res.data.indexOf(res.code.value);

      if (res.codeName === 'PROJECT_MIDDLE_CODE') {
        if (index < 0) {
          setProjectMiddleCode(res.data.concat(res.code.value));
        } else {
          setProjectMiddleCode(res.data.filter((_, i) => i !== index));
        }
      } else if (res.codeName === 'TOOL_LIST') {
        if (index < 0) {
          setProjectToolCode(res.data.concat(res.code.value));
        } else {
          setProjectToolCode(res.data.filter((_, i) => i !== index));
        }
      }
    },
    []
  );

一种方法是创建 res.codeName 到您的函数的映射:

const { codeName, code, data } = res;
const index = data.indexOf(code.value);

const funcMap = {
  PROJECT_MIDDLE_CODE: setProjectMiddleCode,
  TOOL_LIST: setProjectToolCode
}


const newData = index < 0 ? data.concat(code.value) : data.filter((_, i) => i !== index);

const func = funcMap[codeName];

func(newData);