我的组件中出现此错误。只要“完成”错误就会发生错误。国家以任何方式改变。当状态被更改时,问题的根源在getValidationState()中。它不会破坏我的应用程序,但是,我有兴趣知道我在这个组件中做错了什么以及如何为将来修复它。
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import { FormGroup, ControlLabel, FormControl, HelpBlock } from 'react-bootstrap';
class FormGroupValidation extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
completed: false
};
this.getValidationState = this.getValidationState.bind(this);
this.complete = this.complete.bind(this);
this.unComplete = this.unComplete.bind(this);
this.toggleComplete = this.toggleComplete.bind(this);
this.handleChange = this.handleChange.bind(this);
}
getValidationState() {
const length = this.state.value.length;
if (this.ThresholdType === 'max') {
if (this.props.errorLen && length <= this.props.errorLen) {
return 'error';
} else if (this.props.warnLen && length <= this.props.warnLen) {
this.unComplete();
return 'warning';
} else if (this.props.successLen && length <= this.props.successLen) {
this.complete();
return 'success';
}
} else {
if (this.props.successLen && length >= this.props.successLen) {
this.complete();
return 'success';
} else if (this.props.warnLen && length >= this.props.warnLen) {
return 'warning';
} else if (this.props.errorLen && length >= this.props.errorLen) {
this.unComplete();
return 'error';
}
}
}
complete() {
if (!this.state.completed) this.toggleComplete();
}
unComplete() {
if (this.state.completed) this.toggleComplete();
}
toggleComplete() {
this.setState({completed: !this.state.completed});
}
handleChange(e) {
this.setState({ value: e.target.value });
}
render() {
return (
<form>
<FormGroup
controlId="formBasicText"
validationState={this.getValidationState()}
>
<ControlLabel>Working example with validation</ControlLabel>
<FormControl
type="text"
value={this.state.value}
placeholder="Enter text"
onChange={this.handleChange}
/>
<FormControl.Feedback />
<HelpBlock>Validation is based on string length. </HelpBlock>
</FormGroup>
</form>
);
}
}
export default FormGroupValidation;
答案 0 :(得分:0)
看起来你有一个循环。
在你渲染的FormGroup JSX中,你有这个属性:validationState={this.getValidationState()}
所以当你渲染时,它会调用那个函数。通过后续函数调用,您最终会更改toggleComplete()
函数中的状态。当你改变状态时,它会触发重新渲染,循环重新开始(这个后续渲染调用getValidationState()来调用等等)
React应该是被动的(有趣的是:P),即状态在响应中发生变化。