2017-08-13 22 views
-1

既存の状態遷移時に更新できません:警告:SETSTATE(...)は:私は次のエラーを取得しています

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: '/' }}/>; 
    } 

    ... 

回避する方法上の任意の提案この警告?これはあなたがリダイレクトを扱う方法ではありませんか?

+0

あなたのコンストラクタは見えますか? –

+0

@HanaAlaydrusが追加されました – AnApprentice

+0

あなたの例では、状態を設定している場所が表示されません。警告は、コンストラクタまたはレンダリングメソッドで呼び出すことを警告します。これが起こっている場所を見つけて、 '' setState''をリファクタリングする必要があります。 – archae0pteryx

答えて

2

this.inviteAlreadyUsed();

0

まず、inviteAlreadyUsed()機能をバインドする必要があります。矢印機能() => {}を使用することができます。

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

第2に、コンストラクタでpropsを使用して状態を設定したようです。 componentWillMount()に設定する方が良い方法かもしれません。状態を更新>減速 - - >それは呼んで新しいレンダリング - >this.inviteAlreadyUsed();は - >減速機は、状態を更新し、何度も何度も...

ちょうどレンダリングでinviteAlreadyUsedを呼び出さないレンダリングで

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

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

申し訳ありませんが、何が違うのですか? – AnApprentice

+0

@AnApprentice私は自分の答えを編集しました –

関連する問題