reactjs setState not changing state



我有一个函数(onClickAddSection(,当它被调用时,它应该将状态设置为空字符串,但它根本不这样做。请看一下代码,告诉我我做错了什么,谢谢。

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>
    );
}

}

onClickAddSection 函数不会将部分名称设置回 ''。

添加关闭按钮:

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>);

};

你正在使用 Redux 吗? 如果是这样,this.props.saveSection 会进行任何 Ajax 调用?。如果是这样,可能是您使用 setState 更新本地状态,然后您的 Ajax 响应将其重新更新为接收到的值?

试试看setState的功能版本。

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

当您单击该按钮时,onSectionNameChangeonClickAddSection同时发生并且会发生冲突(因为名称设置为空白意味着它的名称正在更改^^(,那么如何在onSectionNameChange中不为sectionName设置状态:

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

我想是的,如果有的话,请在这里发布一些错误,谢谢

最新更新