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

javascript - How to add data to state object in react? - Stack Overflow

programmeradmin2浏览0评论

I created this.state.data object. Now I need to put this.state.email and this.state.password into this.state.data.email2 and this.state.data.password2

I want to create local storage. To do that I need an object where I could store data. this.state.email and this.state.password are inputs.

class Register extends Component {
  constructor(props){
    super(props);

    this.state = {
      email: '',
      password: '',
      data: {
        email2: '',
        password2: '',
      },
    }

    // This binding is necessary to make `this` work in the callback 
    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

  }

  handleEmailChange = (event) => {
    this.setState({email: event.target.value});
  }
  handlePasswordChange = (event) => {
    this.setState({password: event.target.value});
  }

  handleSubmit = (event) => {
    event.preventDefault();

    console.log(this.state.email);
    console.log(this.state.password);

    /*
    Take values from input, ant put it into this state data array
    */

  // Reset form;
    this.setState({
      email: '',
      password: '',
    })
  }

When I activate handleSubmit method I expect to take this.state.email, and this.state.password. And put it into object this.state.data

I created this.state.data object. Now I need to put this.state.email and this.state.password into this.state.data.email2 and this.state.data.password2

I want to create local storage. To do that I need an object where I could store data. this.state.email and this.state.password are inputs.

class Register extends Component {
  constructor(props){
    super(props);

    this.state = {
      email: '',
      password: '',
      data: {
        email2: '',
        password2: '',
      },
    }

    // This binding is necessary to make `this` work in the callback 
    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

  }

  handleEmailChange = (event) => {
    this.setState({email: event.target.value});
  }
  handlePasswordChange = (event) => {
    this.setState({password: event.target.value});
  }

  handleSubmit = (event) => {
    event.preventDefault();

    console.log(this.state.email);
    console.log(this.state.password);

    /*
    Take values from input, ant put it into this state data array
    */

  // Reset form;
    this.setState({
      email: '',
      password: '',
    })
  }

When I activate handleSubmit method I expect to take this.state.email, and this.state.password. And put it into object this.state.data

Share Improve this question edited Feb 18, 2019 at 10:58 JuMoGar 1,7603 gold badges23 silver badges51 bronze badges asked Feb 18, 2019 at 10:28 Arnas DičkusArnas Dičkus 6751 gold badge13 silver badges29 bronze badges 3
  • 2 What is the issue you are facing with storing them to data object? – Agney Commented Feb 18, 2019 at 10:34
  • 2 "// This binding is necessary to make this work in the callback " you don't need to bind those arrow functions. – Yury Tarabanko Commented Feb 18, 2019 at 10:36
  • I'm not sure how. In handleEmailChange i can't put this.setState({data.email2}). – Arnas Dičkus Commented Feb 18, 2019 at 10:38
Add a ment  | 

3 Answers 3

Reset to default 2

Hope you need to pass this.state.email and this.state.password to this.state.data

You can do that in handleEmailChange and handlePasswordChange itself, and your using arrow functions, so don't need to bind this in constructor.

Check a code below:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
      data: {
        email2: '',
        password2: '',
      },
    }
  }
   handleEmailChange = (event) => {
    this.setState({ 
      email: event.target.value,
      data: {
        ...this.state.data,
        email2: event.target.value,
      }  
    });
  }
  handlePasswordChange = (event) => {
    this.setState({
      password: event.target.value,
      data: {
        ...this.state.data,
        password2: event.target.value,
      } 
    });
  }

  handleSubmit = (event) => {
    event.preventDefault();

    console.log(this.state.email);
    console.log(this.state.password);
    console.log('object data');
     console.log(this.state.data);

    /*
    Take values from input, ant put it into this state data array
    */

  // Reset form;
    this.setState({
      email: '',
      password: '',
    }, () => console.log(this.state))
  }

  render() {
    return (
      <div>
        <input type="text" onChange={this.handleEmailChange} value={this.state.email} />
        <br/><br/>
        <input type="text" onChange={this.handlePasswordChange} value={this.state.password} />
        <br/><br/>
        <button type="button" onClick={this.handleSubmit}>Submit</button>
      </div>
    );
  }
}

Working demo

and don't need to write separate events for similar functionalities, Check the demo once, you can do it like below:

<input type="text" data-field = "email" onChange={this.handleChange} value={this.state.email} />
<input type="text"  data-field = "password" onChange={this.handleChange} value={this.state.password} />

and in handleChange

handleChange = (event) => {
    this.setState({ 
     [event.target.getAttribute('data-field')]: event.target.value,
      data: {
        ...this.state.data,
        [`${event.target.getAttribute('data-field')}2`]: event.target.value,
      }  
    });
  }

Hope this helps.

Like this (assuming your setup supports spread operator ... )

handleEmailChange = event => {
    this.setState({ email: event.target.value });
    this.setState(prevState => ({ data: { ...prevState.data, email2: event.target.value } }));
};
handlePasswordChange = event => {
    this.setState({ password: event.target.value });
    this.setState(prevState => ({ data: { ...prevState.data, password2: event.target.value } }));
};

You can do like this

handleSubmit = (event) => {
    event.preventDefault();

    console.log(this.state.email);
    console.log(this.state.password);

    const {data} = this.state;
    data.email2 = this.state.email;
    data.password2 = this.state.password;
    this.setState({ data  });

// Reset form;
    this.setState({
    email: '',
    password: '',
    })
}

or without mutating the state (good practice)

this.setState(prevState => ({
    data: {
        ...prevState.data,
        [data.email2]: this.state.email
        [data.password2]: this.state.password
    },
   }));
发布评论

评论列表(0)

  1. 暂无评论