我如何在React挂钩中动态调用方法

时间:2019-07-02 03:06:03

标签: reactjs react-hooks dynamicmethod

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

我希望在我的react挂钩中调用这两个方法,以避免重复的代码。

我想这样做:

//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));
        }
      }
    },
    []
  );

1 个答案:

答案 0 :(得分:0)

一种方法是创建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);