2017-08-13 70 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 added – AnApprentice

+0

您的示例沒有顯示您設置狀態的位置......警告提示您在構造函數或渲染方法中調用它。你必須找到它發生的地方,然後重構'''setState''' – archae0pteryx

回答

2

this.inviteAlreadyUsed();渲染 - >減速機更新的狀態 - >它調用新的渲染 - >this.inviteAlreadyUsed(); - >減速機,再而更新的狀態...

只是不叫inviteAlreadyUsed在渲染。

0

首先,我認爲你應該綁定inviteAlreadyUsed()函數。您可以使用箭頭功能() => {}

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

其次,似乎你在構造函數中設置道具的狀態。將其設置爲componentWillMount()可能是更好的方法。

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我剛剛編輯了我的答案 –

相關問題