0

I wirte a component of radio,when i make 3 radios, radio1 value is 1,radio2 value is 2,radio 2 value is 3,
Then,when i click radio 1,console.log(this.state.value) return me nothing,
when i click radio 2,console.log(this.state.value) return me 1,
when i click radio 3,console.log(this.state.value) return me 2, Is there anything wrong?

import React, { Component } from 'react';
import { FormGroup } from 'react-bootstrap';
import ContentWrapper from '../../Layout/ContentWrapper';

class Single extends Component {

  constructor(props) {
    super(props);
    this.state = {
      value: props.value
    }
  }

  valueChange = (e) => {
    this.setState({value: e.target.value});
    console.log(this.state.value);
  }

  getSingleChoice = (qItems) => {
    let items = Object.keys(qItems).map((k, index) => {
      let item = qItems[k];
      return (
        <div
          className="radio c-radio"
          id={this.props.id + "_" + k}
          key={this.props.id + "_" + k}
          onChange={e => this.valueChange(e)}>
          <label>
            <input
              type="radio"
              name={"radio" + this.props.id}
              value={item.value}
              defaultChecked={this.state.value == item.value}/>
            <em className="fa fa-circle"></em>{item.label}</label>
        </div>
      );
    });
    return (
      <FormGroup>{items}</FormGroup>
    );
  };

  render() {
    let title = this.props.id + '. ' + this.props.title ';
    return (
      <ContentWrapper>
        <div className="panel panel-default">
          <div className="panel-heading">{title}</div>
          <div className="panel-body">
            {this.getSingleChoice(this.props.options)}
          </div>
        </div>
      </ContentWrapper>
    );
  }
}

export default Single;
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
yang
  • 183
  • 12
  • Possible duplicate of [Why calling setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately) – Mayank Shukla Aug 30 '17 at 07:26

1 Answers1

2

setState is async. If you want to check its results use its second argument and pass callback handler where you can actually see the changed state. For example:

this.setState({value: e.target.value}, () => console.log(this.state.value));
Amid
  • 21,508
  • 5
  • 57
  • 54
  • You should not be sorry. Its OK to make mistakes as long as you are willing to fix them. – Amid Aug 30 '17 at 07:38