简体   繁体   中英

React.js - Value of checkbox not reflecting initial state

I'm rendering checkboxes with the following code:

export default class Day extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            startTime: this.props.startTime,
            endTime: this.props.endTime,
            available: this.props.available
        }
        console.log(this.state.available)
    }

    return (
        <div className='day'>
            <label className='name'>
                {day.name}
                <input
                    type='checkbox'
                    checked={this.state.available}
                    onChange={this.handleAvailableChange}
                    />
            </label>
            {this.state.available}

        </div>
    );
}

This Day component is rendered from a parent component like so:

export default class Schedule extends React.Component {

    render () {
        const dayComponents = this.props.days.map( (day) =>
            <Day key={day.id}
                startTime={this.state[day.name].start}
                endTime={this.state[day.name].end}
                available={this.state[day.name].available}
                day={day}
                handleDayChange={(day, startOrEnd, time, available) => this.handleDayChange(day, startOrEnd, time, available) }
            />

        return (
            <div>
                {dayComponents}
            </div>
        );
    }
}

... where this.props.days is an array of day objects that look like so:

#<Day id: 14, name: "Saturday">

And a state that looks like so:

{"Sunday": {"start": 0, "end": 0, "available": true},
"Monday": {"start": 0, "end": 0, "available": true},
etc...}

The value of my checkbox should be initialized based on the value of this.state.available , but every checkbox is checked when the component is rendered.

I'm looking at the value of this.state.available in two different places, and in both places, I get 5 trues and 2 falses.

Is there some aspect of the component life cycle that I'm missing here? Do I need to utilize something like getInitialState() (didn't change anything when I tried)?

Hoping this is something simple and stupid I overlooked since it seems like such basic functionality...

Edit:

I've removed state from the Day component and rendering the checkboxes as follows:

<label className='name'>
    {day.name}
    <input
        type='checkbox'
        checked={this.props.available}
        onChange={this.handleAvailableChange}
        />
</label>
{this.props.available}

However, this is still the output I get:

屏幕盖

It is also worth noting that if I assign a static false to the value of checked , an unchecked checkbox is returned.

Edit 2 (Solution):

Turns out that when I was saving the schedule to my database (which is where I pull the available values from), I was saving the booleans to strings because the parameters in the AJAX request were getting automatically cast to a different data type.

So I was trying to set the value of checked to "false" , which always returns true since it's an existent string.

Since you are managing the state by the parent component, i will suggest you to not store the values again in child component, directly use this.props.keyName . You are passing a change function also, use that method to update the parent state value, once you update the parent state , updated values will get passed to child component automatically. On re-render it will reflect all the changes in ui also.

Check this working snippet:

 let days = [ {name:"Sunday"}, {name:"Monday"}, {name:"Tuesday"}, {name:"Wednesday"}, {name:"Thursday"}, {name:"Friday"}, {name:"Saturday"}, ]; class Schedule extends React.Component { constructor(){ super(); this.state={ "Sunday": {"start": 0, "end": 0, "available": true}, "Monday": {"start": 0, "end": 0, "available": true}, "Tuesday": {"start": 0, "end": 0, "available": true}, "Wednesday": {"start": 0, "end": 0, "available": true}, "Thursday": {"start": 0, "end": 0, "available": true}, "Friday": {"start": 0, "end": 0, "available": false}, "Saturday": {"start": 0, "end": 0, "available": false}, } } handleDayChange(value, dayName){ let obj = {...this.state[dayName]}; obj.available = value; this.setState({[dayName]: obj}); } render () { const dayComponents = this.props.days.map(day => <Day key={day.name} startTime={this.state[day.name].start} endTime={this.state[day.name].end} available={this.state[day.name].available} name={day.name} handleDayChange={(value, dayName) => this.handleDayChange(value, dayName) } /> ) return ( <div> {dayComponents} </div> ); } } class Day extends React.Component { constructor(props){ super(props) this.state = { } this.handleAvailableChange = this.handleAvailableChange.bind(this); } handleAvailableChange(e){ this.props.handleDayChange(e.target.checked, this.props.name); } render(){ let values = this.props; return ( <div className='day'> <label className='name'> {values.name} <input type='checkbox' checked={values.available} onChange={this.handleAvailableChange} /> </label> {values.available + ""} </div> ); } } ReactDOM.render(<Schedule days={days}/>, document.getElementById('app')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='app'/> 

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