ReactJS:警告:setState(...):在现有状态转换期间无法更新 [英] ReactJS: Warning: setState(...): Cannot update during an existing state transition
问题描述
我试图从渲染视图重构以下代码:
I am trying to refactor the following code from my render view:
<Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChange.bind(this,false)} >Retour</Button>
到绑定在构造函数中的版本。这是因为渲染视图中的绑定会给我带来性能问题,尤其是在低端手机上。
to a version where the bind is within the constructor. The reason for that is that bind in the render view will give me performance issues, especially on low end mobile phones.
我创建了以下代码,但我不断收到以下错误(很多错误)。看起来应用程序进入循环:
I have created the following code, but I am constantly getting the following errors (lots of them). It looks like the app gets in a loop:
Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
下面是我使用的代码:
var React = require('react');
var ButtonGroup = require('react-bootstrap/lib/ButtonGroup');
var Button = require('react-bootstrap/lib/Button');
var Form = require('react-bootstrap/lib/Form');
var FormGroup = require('react-bootstrap/lib/FormGroup');
var Well = require('react-bootstrap/lib/Well');
export default class Search extends React.Component {
constructor() {
super();
this.state = {
singleJourney: false
};
this.handleButtonChange = this.handleButtonChange.bind(this);
}
handleButtonChange(value) {
this.setState({
singleJourney: value
});
}
render() {
return (
<Form>
<Well style={wellStyle}>
<FormGroup className="text-center">
<ButtonGroup>
<Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChange(false)} >Retour</Button>
<Button href="#" active={this.state.singleJourney} onClick={this.handleButtonChange(true)} >Single Journey</Button>
</ButtonGroup>
</FormGroup>
</Well>
</Form>
);
}
}
module.exports = Search;
推荐答案
看起来你不小心调用 handleButtonChange
方法,你可能想做 onClick = {()=>
Looks like you're accidentally calling the handleButtonChange
method in your render method, you probably want to do onClick={() => this.handleButtonChange(false)}
instead.
如果你不想在onClick处理程序中创建一个lambda,我想你'需要有两个绑定方法,每个参数一个
If you don't want to create a lambda in the onClick handler, I think you'll need to have two bound methods, one for each parameter.
在构造函数
:
this.handleButtonChangeRetour = this.handleButtonChange.bind(this, true);
this.handleButtonChangeSingle = this.handleButtonChange.bind(this, false);
在 render
p>
And in the render
method:
<Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChangeSingle} >Retour</Button>
<Button href="#" active={this.state.singleJourney} onClick={this.handleButtonChangeRetour}>Single Journey</Button>
这篇关于ReactJS:警告:setState(...):在现有状态转换期间无法更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!