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

时间:2017-08-13 16:08:13

标签: reactjs react-redux

我收到以下错误:

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`.

我的组件:

import React from 'react';
import { Redirect } from 'react-router'
import Notifications from 'react-notification-system-redux';

  constructor(props) {
    super(props);
    this.state = {
      invite_token: this.props.match.params.token,
      FormSubmitSucceeded: false,
      inviteRequestSubmitSucceeded: false
    };
  }

  ....

  inviteAlreadyUsed() {
    const notificationOpts = {
      message: 'Invitation already used!',
    };
    this.props.createNotificationSuccess(notificationOpts);
  }

  render() {
    const { invite } = this.props;

    if (invite && invite.status === "completed") {
      this.inviteAlreadyUsed();
      return <Redirect to={{ pathname: '/' }}/>;
    }

  ...

有关如何避免此警告的任何建议?这不是你如何处理重定向?

2 个答案:

答案 0 :(得分:2)

渲染中的

this.inviteAlreadyUsed(); - &gt; reducer更新状态 - &gt;它称为新渲染 - &gt; this.inviteAlreadyUsed(); - &gt; reducer更新状态,一次又一次......

请勿在渲染中致电inviteAlreadyUsed

答案 1 :(得分:0)

首先,我认为你应该绑定inviteAlreadyUsed()函数。您可以使用箭头函数() => {}

inviteAlreadyUsed = () => {
    const notificationOpts = {
       message: 'Invitation already used!',
    };
    this.props.createNotificationSuccess(notificationOpts);
}

其次,好像你在构造函数中使用props设置状态。在componentWillMount()中设置它可能是一种更好的方法。

  constructor(props) {
    super(props);
    this.state = {
      invite_token: '',
      FormSubmitSucceeded: false,
      inviteRequestSubmitSucceeded: false
    };
  }

  componentWillMount() {
    this.setState({
      invite_token: this.props.match.params.token
    })
  }