最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change state of nested object props based on user input handleChange - Stack Overflow

programmeradmin5浏览0评论

I have this ponent state

this.state = {
      title: "",
      salary: {
        min: "",
        max: "",
        single: ""
      }
}

I use this function for handling user input

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

it works with

<input type="text" id="title" name="title" onChange={this.handleInputChange}/>

Can I use such a function to change this.state.salary.min/max ...

I mean can this type of function work with nested objects in state and <input/> name art?

I have this ponent state

this.state = {
      title: "",
      salary: {
        min: "",
        max: "",
        single: ""
      }
}

I use this function for handling user input

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

it works with

<input type="text" id="title" name="title" onChange={this.handleInputChange}/>

Can I use such a function to change this.state.salary.min/max ...

I mean can this type of function work with nested objects in state and <input/> name art?

Share edited Feb 7, 2018 at 20:21 Josh Pittman 7,3648 gold badges44 silver badges67 bronze badges asked Feb 7, 2018 at 18:58 Георги ДимитрановГеорги Димитранов 1,3091 gold badge12 silver badges22 bronze badges 2
  • You're gonna have to give us a little more info, and maybe format the question a little better. What exactly isn't working? Could you provide an example? – ZekeDroid Commented Feb 7, 2018 at 19:00
  • i have state prop called title i use this function and chnage the state based on the name of the input field and its value , my question is ... can this type of logic work for nested objects in state (e.g. salary.min) – Георги Димитранов Commented Feb 7, 2018 at 19:02
Add a ment  | 

2 Answers 2

Reset to default 4

Yes you can, but you need to update whole nested object.

You have several options:

Object.assign()

const salary = Object.assign({}, this.state.salary, { min: minValue });

this.setState({ salary });

Spread operator

const salary =  {
    ...this.state.salary,
    min: minValue
}

this.setState({ salary });

Immutable data structure

Immutable.js

this.state = {
    salary = Immutable.Map({ 
        min: 8,
        max: 10
    });
};

const salary = this.state.salary.set('min', minValue);

this.setState({ salary });

Immutability helper

See https://reactjs/docs/update.html

const salary = update(this.state.salary, {
    min: minValue
});

this.setState({ salary });

Yes, you can do that by using spread operator in setState.

this.setState(prevState => ({
    ...prevState,
    salary: {
        ...prevState.salary,
        min: newMinValue
    }
}))

Or, you can use Object.assign() if you are using ES5.

this.setState({
  salary: Object.assign({}, this.state.salary, {min: newMinValue})
});
发布评论

评论列表(0)

  1. 暂无评论