修改嵌套对象中的值

时间:2020-04-10 16:23:52

标签: javascript reactjs material-ui

我有一个嵌套对象:

{
    id: "id",
    name: "Name",
    type: "SC",
    allgemein: {
      charname: "Name",
      spieler: "Jon",
    },
    eigenschaften: {
      lebenspunkte: "30",
    },
    talente: {},
    zauber: {},
  }

我正在使用表单创建一个新对象。大部分都可以,但是在功能handleSubmit中,我试图将嵌套的spieler设置为"TEST"

import React from "react";
    import { TextField, Button } from "@material-ui/core/";

    export default class extends React.Component {
      state = this.getInitState();

      getInitState() {
        const { charakterID } = this.props;

        return charakterID
          ? charakterID
          : {
              name: "",
              allgemein: {
                charname: "",
                spieler: "",
              },
              eigenschaften: {},
              talente: {},
              zauber: {},
            };
      }

      componentWillReceiveProps({ charakterID }) {
        this.setState({
          ...charakterID,
        });
      }

      handleChange = (n) => ({ target: { value } }) => {
        this.setState({
          [n]: value,
        });
      };

      handleChangeAllg = (n) => ({ target: { value } }) => {
        this.setState((prevState) => ({
          ...prevState,
          allgemein: {
            ...prevState.allgemein,
            charname: value,
          },
        }));
      };

      handleSubmit = () => {
        this.props.onSubmit({
          id: this.state.name.toLocaleLowerCase().replace(/ /g, "-"),
          type: "SC",
          allgemein: {spieler: "TEST"},
          ...this.state,
        });

        this.setState(this.getInitState());
      };

      render() {
        const {
            name,
            allgemein: { charname },
          } = this.state,
          { charakterID } = this.props;

        console.log("fired");
        console.log(this.props.onCreate);

        return (
          <form>
            <TextField
              label="name"
              value={name}
              onChange={this.handleChange("name")}
              margin="dense"
              fullWidth
            />
            <br />
            <TextField
              label="charname"
              value={charname}
              onChange={this.handleChangeAllg("charname")}
              margin="dense"
              fullWidth
            />
            <br />
            <Button color="primary" variant="contained" onClick={this.handleSubmit}>
              {charakterID ? "Edit" : "Neu"}
            </Button>
          </form>
        );
      }
    } 

这行不通,我也不知道为什么。你能帮我吗?

1 个答案:

答案 0 :(得分:1)

尝试一下是否可行

useState