[英]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函数不会将sectionName设置回。
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>);
};
您在使用Redux吗? 如果是这样,this.props.saveSection会进行Ajax调用吗? 如果是这样,可能是您使用setState更新了本地状态,然后您的Ajax响应又将其更新为接收到的值了吗?
只需尝试看看setState
的功能版本即可。
this.setState(function (state, props) {
return {
sectionName:'',
validation:false
}
});
似乎当您单击按钮时, onSectionNameChange
和onClickAddSection
会同时发生,并且会发生冲突(因为名称设置为空意味着其名称已更改^^),那么如何不在onSectionNameChange中设置sectionName的onSectionNameChange
:
onSectionNameChange(event) {
if(this.state.validation==false){
this.setState({validation:true});
}
//this.setState({sectionName: event.target.value});
}
我想是的,请在此处发布一些错误(谢谢)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.