ReactJS:警告:setState(...):无法在现有状态转换期间更新

ReactJS: Warning: setState(...): Cannot update during an existing state transition

我正在尝试从渲染视图重构以下代码:

<Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChange.bind(this,false)} >Retour</Button>

绑定在构造函数中的版本。原因是渲染视图中的绑定会给我带来性能问题,尤其是在低端手机上。

我创建了以下代码,但我不断收到以下错误(很多)。应用似乎进入了循环:

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={() => this.handleButtonChange(false)}

如果您不想在 onClick 处理程序中创建 lambda,我认为您需要有两个绑定方法,每个参数一个。

constructor中:

this.handleButtonChangeRetour = this.handleButtonChange.bind(this, true);
this.handleButtonChangeSingle = this.handleButtonChange.bind(this, false);

并且在 render 方法中:

<Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChangeSingle} >Retour</Button>
<Button href="#" active={this.state.singleJourney} onClick={this.handleButtonChangeRetour}>Single Journey</Button>

如果您尝试向 recompose 中的处理程序添加参数,请确保您在处理程序中正确定义了参数。它本质上是一个柯里化函数,因此您要确保需要正确数量的参数。 This page has a good example of using arguments with handlers.

示例(来自 link):

withHandlers({
  handleClick: props => (value1, value2) => event => {
    console.log(event)
    alert(value1 + ' was clicked!')
    props.doSomething(value2)
  },
})

对于您的 child HOC 和 parent

class MyComponent extends Component {
  static propTypes = {
    handleClick: PropTypes.func, 
  }
  render () {
    const {handleClick} = this.props
    return (
      <div onClick={handleClick(value1, value2)} />
    )
  }
}

这避免了从您的处理程序中编写匿名函数来修补因未在您的处理程序上提供足够的参数名称而导致的问题。

我在调用时遇到了同样的错误

this.handleClick = this.handleClick.bind(this);

在我的构造函数中,当 handleClick 不存在时

(我已经删除了它并且不小心在我的构造函数中留下了 "this" 绑定语句)。

解决方案 = 删除 "this" 绑定语句。

来自 React 文档 Passing arguments to event handlers

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

我使用的组件打开Popover的方案是reactstrap (React Bootstrap 4 components)

    class Settings extends Component {
        constructor(props) {
            super(props);

            this.state = {
              popoversOpen: [] // array open popovers
            }
        }

        // toggle my popovers
        togglePopoverHelp = (selected) => (e) => {
            const index = this.state.popoversOpen.indexOf(selected);
            if (index < 0) {
              this.state.popoversOpen.push(selected);
            } else {
              this.state.popoversOpen.splice(index, 1);
            }
            this.setState({ popoversOpen: [...this.state.popoversOpen] });
        }

        render() {
            <div id="settings">
                <button id="PopoverTimer" onClick={this.togglePopoverHelp(1)} className="btn btn-outline-danger" type="button">?</button>
                <Popover placement="left" isOpen={this.state.popoversOpen.includes(1)} target="PopoverTimer" toggle={this.togglePopoverHelp(1)}>
                  <PopoverHeader>Header popover</PopoverHeader>
                  <PopoverBody>Description popover</PopoverBody>
                </Popover>

                <button id="popoverRefresh" onClick={this.togglePopoverHelp(2)} className="btn btn-outline-danger" type="button">?</button>
                <Popover placement="left" isOpen={this.state.popoversOpen.includes(2)} target="popoverRefresh" toggle={this.togglePopoverHelp(2)}>
                  <PopoverHeader>Header popover 2</PopoverHeader>
                  <PopoverBody>Description popover2</PopoverBody>
                </Popover>
            </div>
        }
    }

问题肯定出在使用 onClick 处理程序渲染按钮时的 this 绑定。解决方案是在渲染时调用动作处理程序时使用箭头函数。像这样: onClick={ () => this.handleButtonChange(false) }

为了更好地理解,我给出了一个通用的例子,在下面的代码中

render(){
    return(
      <div>

        <h3>Simple Counter</h3>
        <Counter
          value={this.props.counter}
          onIncrement={this.props.increment()} <------ calling the function
          onDecrement={this.props.decrement()} <-----------
          onIncrementAsync={this.props.incrementAsync()} />
      </div>
    )
  }

当提供道具时我直接调用函数,这将有一个无限循环执行并会给你那个错误,删除函数调用一切正常。

render(){
    return(
      <div>

        <h3>Simple Counter</h3>
        <Counter
          value={this.props.counter}
          onIncrement={this.props.increment} <------ function call removed
          onDecrement={this.props.decrement} <-----------
          onIncrementAsync={this.props.incrementAsync} />
      </div>
    )
  }

render() 调用中完成的任何状态更改都会发出相同的警告。

一个棘手的例子: 当基于状态数据呈现多 select GUI 组件时,如果状态没有可显示的内容,则对 resetOptions() 的调用被视为该组件的状态更改。

明显的解决方法是在 componentDidUpdate() 中执行 resetOptions() 而不是 render()

这通常发生在你打电话时

onClick={this.handleButton()} - 注意 () 而不是:

onClick={this.handleButton} - 注意这里我们在初始化函数时没有调用它

问题 在这里:onClick={this.handleButtonChange(false)}

当您将 this.handleButtonChange(false) 传递给 onClick 时,您实际上是在使用 value = false 调用函数并将 onClick 设置为函数的 return 值,该值未定义。此外,调用 this.handleButtonChange(false) 然后调用 this.setState() 触发重新渲染,导致无限渲染循环。

解决方案 是在 lambda 中传递函数:onClick={() => this.handleButtonChange(false)}。在这里,您将 onClick 设置为等于单击按钮时将调用 handleButtonChange(false) 的函数。

以下示例可能会有所帮助:

function handleButtonChange(value){
  console.log("State updated!")
}

console.log(handleButtonChange(false))
//output: State updated!
//output: undefined

console.log(() => handleButtonChange(false))
//output: ()=>{handleButtonChange(false);}

onClick 函数必须通过 returns handleButtonChange() 方法的函数。否则它将自动 运行,以 error/warning 结束。使用以下方法解决问题。

onClick={() => this.handleButtonChange(false)}