0

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

我希望在我的反应钩子中调用这两个方法以避免重复代码。

我想这样做:

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

1 回答 1

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);
于 2019-07-02T04:32:00.767 回答