React Redux - 动态调度函数名称

React Redux - Dynamically dispatch function name

我目前正在 React Native 中使用 react-redux 开发一个项目。

现在我想用动态输入调用调度挂钩。然而它就是不起作用,但我在控制台中没有收到任何错误消息。

一些备注:

谁能告诉我,我做错了什么?

我当前的代码:

import {
  resetCompleteStoreState,
  setAdressCity,
  setAdressZipcode,
  setEmail,
  setName,
  setPhone,
} from "../../../app/redux/features/auth/userSlice";

... more Code ... 

  var functions = new Map();
  [setAdressCity, setAdressZipcode, setEmail, setName, setPhone].forEach(
    (fn) => {
      functions.set("" + fn, fn);
    }
  );

      for (let [key, value] of Object.entries(response.data.data.user)) {
        if (key.includes("_")) {
          var i,
            frags = key.split("_");
          for (i = 0; i < frags.length; i++) {
            frags[i] = frags[i].charAt(0).toUpperCase() + frags[i].slice(1);
          }
          key = frags.join("");
        } else {
          key = key.charAt(0).toUpperCase() + key.slice(1);
        }
        if (key != "Id") {
          stateMethod = functions.get("user/set" + key);
          dispatch(stateMethod(value));        
        }
      }

你不能从字符串中调用函数,除非你将它们存储在一些进行翻译的对象中

像这样

import {
  resetCompleteStoreState,
  setAdressCity,
  setAdressZipcode,
  setEmail,
  setName,
  setPhone,
} from "../../../app/redux/features/auth/userSlice";

... more Code ... 
    const functions = new Map()
    [ setAdressCity,
  setAdressZipcode,
  setEmail,
  setName,
  setPhone].forEach(fn => {
    functions.set(fn.name, fn)
  })
      for (let [key, value] of Object.entries(response.data.data.user)) {
        if (key.includes("_")) {
          var i,
            frags = key.split("_");
          for (i = 0; i < frags.length; i++) {
            frags[i] = frags[i].charAt(0).toUpperCase() + frags[i].slice(1);
          }
          key = frags.join("");
        } else {
          key = key.charAt(0).toUpperCase() + key.slice(1);
        }
        if (key != "Id") {
          //  dispatch("user/set" + `${key}` + `(${value})`);
          //  dispatch(`set${key}`(`${value}`));
            test = functions["set" + key];
            console.log(test);
           dispatch(test(`${value}`));           
        }
      }