React js Lodash设置状态更改,但状态未更新

时间:2020-02-21 12:12:48

标签: javascript reactjs lodash

我应该将元素的值更改为一定深度,我正在使用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>
  );
}

0 个答案:

没有答案