简体   繁体   中英

reactjs setState not changing state

I have a function(onClickAddSection), when its called, it should set the state to empty string but it doesn't do that at all. Please take a look at the code and tell me what im doing wrong thank you.

class AddNewSectionForm extends Component {
constructor(props) {
    super(props);
    this.state = {
        sectionName: '',
        validation:false
    };
    this.onSectionNameChange = this.onSectionNameChange.bind(this);
    this.onClickAddSection = this.onClickAddSection.bind(this);

}

onSectionNameChange(event) {
    if(this.state.validation==false){
        this.setState({validation:true});
    }
    this.setState({sectionName: event.target.value});
}

onClickAddSection(event) {
    event.preventDefault();
    this.props.saveSection(this.state.sectionName);
    this.setState({sectionName:'',validation:false});
}

render() {
    return (
            <div>
                <TextInput name="newSection" label="Section Name :"
                           onChange={this.onSectionNameChange}
                           value={this.state.sectionName}
                           error = {this.state.validation==true&& this.state.sectionName.length==0?'Enter Section Name':''}/>
                <AddCloseButtons add = {this.onClickAddSection}
                                 close = {this.props.closeCharm}
                                 />
            </div>
    );
}

}

the onClickAddSection function doesn't set the sectionName back to ''.

AddCloseButton:

const AddCloseButtons = ({add,close}) => {
return (
    <div className="form-group">
        <button className="btn btn-primary" style={{width: '40%', border:'solid black 1px'}} onClick={add}>Add</button>
        <button className="btn btn-secondary" style={{width: '40%', float: 'right',border:'solid black 1px'}} onClick={close}>Close</button>
    </div>);

};

Are you using Redux? if so, this.props.saveSection makes any Ajax Call?. If so, could be that you update the local state with setState and then your Ajax response re updates it the received value?

Just try and see the functional version of setState .

this.setState(function (state, props) {
 return {
  sectionName:'',
  validation:false
 }
});

It seems that when you click the button, onSectionNameChange and onClickAddSection happen at the same time and will have conflict (because the name is set to blank means its name is being changed ^^), so how about not setting state for sectionName in onSectionNameChange :

onSectionNameChange(event) {
    if(this.state.validation==false){
        this.setState({validation:true});
    }
    //this.setState({sectionName: event.target.value});
}

I guess so, please post here some errors if any, thanks

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