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



在我的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));
        }
      }
    },
    []
  );

做到这一点的一种方法是为您的功能创建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);

相关内容

  • 没有找到相关文章