2015-06-19 58 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