2015-06-19 44 views
1

我有一個Page.jsx使用Form.jsx組件狀態有效性繼續。要做到這一點,我在Form.jsx這樣做:更新母公司通過回調道具兒童(React.js)

// ... 
allInputsAreValid: function() { 
    return _.all(this.state.inputsValidation, function (inputsValidation) { 
    return inputsValidation.error === false; 
    }); 
} 
// ... 

然後,在render方法Form.jsx

if (this.allInputsAreValid()) { 
    this.props.isValid(); 
} else { 
    this.props.isInvalid(); 
} 

最後,方法enable/disableButton(上Form.jsx):

// ... 
enableButton: function() { 
    this.setState({ 
    canSubmit: true 
    }); 
}, 

disableButton: function() { 
    this.setState({ 
    canSubmit: false 
    }); 
} 
//... 

更改這些方法中的狀態,控制檯thr允許錯誤:

Uncaught Error: Invariant Violation: setState(...): Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.

爲什麼?怎麼修?

+0

'

'正在使用'Page.jsx'中的'enableButton' /'disableButton'。當表單有效時,通過allInputsAreValid方法檢查,然後調用其中一個方法。重點是:從那裏改變狀態會導致錯誤。 –

回答

0

您需要將這個邏輯出render方法:

if (this.allInputsAreValid()) { 
    this.props.isValid(); 
} else { 
    this.props.isInvalid(); 
} 

更新:

讓我們修改您的<Input />組件接受onChange道具。我不確定您是否正在使用ES6課程或React.createClass,但我會在此處參加ES6課程路線。

class Input extends React.Component { 
    render() { 
    return <input type="text" onChange={this.props.onChange} />; 
    } 
} 

然後修改Form.jsx給予輸入的onChange財產。

<Form isValid={this.enableButton} isInvalid={this.disableButton}> 
    <Input 
    validation={{ presence: true }} 
    onChange={() => { 
     if (this.allInputsAreValid()) { 
     this.props.isValid(); 
     } else { 
     this.props.isInvalid(); 
     } 
    }} 
    /> 
</Form> 
+0

'componentDidMount'只出現一次。我需要檢查每個狀態的變化。 –

+0

@GuilhermeOderdenge我做了一個更新。讓我知道你是否使用ES6。 –

0

我假設「page.jsx」包含方法「enableButton」和「disableButton」。

在更新狀態時,除了「canSubmit」之外,還有其他任何狀態屬性嗎?如果你有「canSubmit」沿着其他國家財產你迫使他們變​​得不確定這樣做

this.setState({ 
    canSubmit: true 
); 

所以我假設有一個名爲「XYZ」與「canSubmit」國有財產沿着存在的狀態屬性。所以更新下面的狀態

this.setState({ 
    canSubmit: true, 
    xyz:this.state.xyz 
); 

或更好,你嘗試使用反應更新插件來更新狀態。更發現這裏https://facebook.github.io/react/docs/update.html

更新

在你的頁面嘗試下面的代碼。jsx文件

shouldComponentUpdate(object nextProps, object nextState){ 
    if(this.state.canSubmit==nextState.canSubmit){ 
     return false 
    } 
    } 
+0

'未捕獲的類型錯誤:無法讀取屬性'_currentElement'的空值 - 不,我只有'canSubmit'到目前爲止。 –

+0

好的。嘗試在page.jsx中包含「shouldComponentUpdate」方法 – pashaplus