简体   繁体   中英

ReactJS How to change value of object stored in state

All code will be below my question and explanation.

So what I am trying to do is update my state which is in a grandparent class, this is done for reasons to do with files, I am also using Material-UI for the text boxes. And I'm also writing Redux without Redux, Because I can just if you see some strange things.

My grandparent class state looks like this:

state = {
  value: 0,
  application: {
    ApplicationPK: '',
    Person: [
      {
        PersonPK: '',
        FullName: '',
        TitleFK: '',
        Forename: '',
        MiddleNames: '',
        Surname: '',
        DateOfBirth: '',
        HomeTelephone: '',
        MobileTelephone: '',
        EmailAddress: '',
        LoanPurposeFK: '',
        MaritalStatusFK: '',
        Addresses: [
          {
            FlatNumber: '',
            BuildingName: '',
            BuildingNumber: '',
            Street: '',
            District: '',
            Town: '',
            County: '',
            Postcode: '',
            ResidentialStatusFK: '',
            DateMovedIn: '',
            IsCurrentAddress: '',
            AddressPK: '',
          },
        ],
        Employment: [
          {
            EmploymentStatusFK: '',
            Employer: '',
            JobTitle: '',
            Telephone: '',
            MonthlyPay: '',
            IsPaidByBACS: '',
            PayFrequencyFK: '',
            DayOfMonth: '',
            DayOfWeek: '',
            NextPayDate: '',
            FollowingPayDate: '',
            DateStarted: '',
            Postcode: '',
            EmploymentPK: '',
            Website: '',
          },
        ],
        BankAccount: [
          {
            Name: '',
            Sortcode: '',
            AccountNumber: '',
            IsAccountHolder: '',
            IsJointHolder: '',
            IsSoleAuthoriseDebits: '',
            IsPrimary: '',
            IsActive: '',
            BankAccountPK: '',
          },
        ],
      },
    ],
  },
};

I know its long but thats because it errors because mui text boxes dont like null values on load.

this is how im changing the state at the moment but its adding it as a value at the top level of the state and i want it to obviously replace the value that is inside person. this function is in the same class as the state obviously

 handleChangeType = event => {
   this.setState({ [event.target.name]: event.target.value });
 }

and Finally the Mui Text Box looks like this:

<Input
   defaultValue={this.props.state.application.Person[0].Forename}
   className={classes.input}
   onChange={this.props.handleChangeType}
   name="Forename"
   inputProps={{
     'aria-label': 'Description',
   }}
/>

TL:DR: How do i update the correct value in the state

I know its long but thats because it errors because mui text boxes dont like null values on load.

To avoid initializing a bunch of empty strings everywhere, you could just do:

defaultValue={((this.props.state.application || {}).Person[0] || {}).Forename || ""}

As per updating the correct state variable, I would use a different handler for each category. You must also bear in mind that your state variable here is the Person array. If you want to update anything within it, you need to pass a new array to the state. Finally, you seem to want to be able to have multiple users inside your Persons array, but your event handlers aren't given any info of which user you want to update field X or Y.

For example:

handleChangeType = (userIndex, name, event) => {
  let person = Object.assign({}, this.state.Persons[userIndex]);  //shallow-copy
  person[name] = event.target.value
  this.setState({Person: person });
}

For each object or array that's nestled, you'll need to create a copy, change the copy and then replace the original with the copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM