在我的 React 钩子中,我定义了两个用于设置变量的函数:
setProjectMiddleCode
和setProjectToolCode
.
我希望在我的反应钩子中调用这两个方法以避免重复代码。
我想这样做:
//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));
}
}
},
[]
);