【问题标题】:React js lodash set the state changes but the state is not updatedReact js lodash设置状态更改但状态未更新
【发布时间】:2025-12-16 22:50:02
【问题描述】:

我应该将元素的值更改为某个深度,我正在使用 lodash,但我遇到了问题。

我制作了对象的副本,并在副本上应用了 lodash 集,我修改了原始对象。

我尝试更改状态,但没有更新。

你可以帮帮我。

链接:codesandbox

代码:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import ReactJson from "react-json-view";
import lodash from "lodash";

const useStyles = makeStyles(theme => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
      width: 200
    }
  }
}));

export default function BasicTextFields() {
  const classes = useStyles();

  const [state, setState] = React.useState({
    name: "James",
    surname: "bond",
    card: {
      id: 7,
      group: "J"
    },
    scope: [{ scope: "user", actions: ["create", "delete"] }]
  });

  const handleChangeField = field => ({ target: { value } }) => {
    let newState = Object.assign(state, {});
    console.log(state, field, value);
    lodash.set(newState, field, value);
    setState(newState);
  };

  console.log("Change", state);

  return (
    <form className={classes.root} noValidate autoComplete="off">
      <ReactJson
        src={state}
        theme={"solarized"}
        enableClipboard={false}
        displayObjectSize={false}
      />

      <TextField
        id="standard-basic"
        label="Name"
        onChange={handleChangeField("name")}
      />
      <TextField
        id="standard-basic"
        label="Group"
        onChange={handleChangeField("card.group")}
      />
      <TextField
        id="standard-basic"
        label="Action[0]"
        onChange={handleChangeField("scope[0].actions[0]")}
      />
    </form>
  );
}

【问题讨论】:

  • Object.assign 是浅拷贝。做一个深拷贝。使用 lodash clonedeep
  • 或者使用不会改变原始对象的 lodash/fp _.set()
  • 我试过了,还是不行。

标签: javascript reactjs lodash


【解决方案1】:

因为 lodash.set 改变了值。你可以使用 lodash/fp。

使用 lodash/fp:

import set from 'lodash/fp/set';

const handleChangeField = field => ({ target: { value } }) => {
    setState(set(field, value, state););
};

this set 返回一个新对象。

【讨论】: