【问题标题】:Set state value using string path key from deeply nested object使用来自深度嵌套对象的字符串路径键设置状态值
【发布时间】:2022-01-12 11:39:07
【问题描述】:

我正在尝试使用键的字符串路径来更改对象内的深层嵌套值以访问该对象。

设置:

const [payload, setPayload] = useState({
    name: "test",
    download: true,
    downloadConfiguration: {
      product: {
        initialDownloadLength: 3,

      }}})

当对象值改变时:

  const handleChange = (prop: any) => (e: React.ChangeEvent<HTMLInputElement>) => {

    if (typeof e.target.value === "number") {
      setPayload({ ...payload, [prop]: parseInt(e.target.value) });
    }

    if (typeof e.target.value === "string") {
      setPayload({ ...payload, [prop]: e.target.value });
    }
  };

当我更改对象最外层的值时,它可以正常工作并更新值,例如

onChange={handleChange("name")}

但我无法访问嵌套在 product 和 downloadConfiguration 中的 initialDownloadLength 键。 我尝试过“downloadConfiguration.product.initialDownloadLength”并使用方括号等,但每次它都会在对象的最顶层创建一个新对象。

【问题讨论】:

  • 不幸的是,这似乎对我不起作用,而只是获取那个键的值,我没有问题得到
  • 如果你可以在键处获取值,你可以在键处设置值...
  • 我可以正常使用“downloadConfiguration.product.initalDownloadLength”访问数据,但是在我需要[prop]中键的字符串值的情况下,它不起作用

标签: javascript reactjs typescript object use-state


【解决方案1】:

您可以在您的 handleChange 方法中使用dynamically-set-property-of-nested-object 中的解决方案,如下所示:

// set method copied from the above link
function set(obj, path, value) {
    var schema = obj; 
    var pList = path.split('.');
    var len = pList.length;
    for(var i = 0; i < len-1; i++) {
        var elem = pList[i];
        if( !schema[elem] ) schema[elem] = {}
        schema = schema[elem];
    }
    schema[pList[len-1]] = value;
}
...

const handleChange = (prop) => (e) => {
  let value;
  if (typeof e.target.value === "number") {
    value = parseInt(e.target.value);
  }

  if (typeof e.target.value === "string") {
    value = e.target.value;
  }

  setPayload((prevState) => { 
     const newState = {...prevState};
     set(newState, prop, value);
     return newState;
 })
};
....

onChange={handleChange("downloadConfiguration.product.initialDownloadLength")}

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 2020-01-07
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多