2015-10-13 25 views
4

我有一些頂級組件(RegisrationPage)與狀態,它通過它狀態/道具轉儲底層組件(InputField,Dropdown,Datepicker)。 底層組件在回調的幫助下更改RegistrationPage的狀態。PureRenderMixin和狀態管理設計

問題: PureRenderMixin不工作,因爲我有綁定傳遞給下一級的組件狀態更改回調。

問:如何使PureRenderMixin作品中最優雅的方式?

讓我們的代碼解釋:

InputBlock:

const React = require('react'), 
     PureRenderMixin = require('react-addons-pure-render-mixin'); 

module.exports = React.createClass({ 
    mixins: [PureRenderMixin], 

    propTypes: { 
     input: React.PropTypes.string, 
     onChange: React.PropTypes.func 
    }, 

    render() { 
     //PROBLEM - is re-rendered each time , since onChange callback each time is an different object due bind method call 
    } 

}); 

RegistrationPage:

RegistrationPage = React.createClass({ 

    /** 
    * Since all state is held by `RegistrationPage` and bottom-level components are dump, 
    * I do _onFieldChange.bind - _onFieldChange should know which field should be changed 
    */ 
    render() { 
     return CreateFragment({ 
      email: <InputBlock 
       input={this.state.email} 
       onChange={this._onFieldChange.bind(self, 'email')}/>, 
      firstName: <InputBlock 
       input={this.state.firstName} 
       onChange={this._onFieldChange.bind(self, 'firstName')}/>, 
      ......... 
     }); 
    }, 

    _onFieldChange(key, event) { 
     //Save registered progress to store and re-render the component 
     AppActionCreators.saveRegisterProgress(this.state); 
    } 
}) 

我的解決方法:只需將inputFieldName作爲額外屬性並在底層組件內進行綁定。

+1

您是否考慮過使用flux-store?我寧願將onChange中的值存儲到flux-store中,而不是使用基於回調的方法 – FranBran

+0

@DERIIIFranz請解釋您的意思 –

+0

看看如何:https://facebook.github.io/flux/docs /overview.html – FranBran

回答

1

問題是.bind()每次調用它時都會返回一個新函數。爲了避免它,你應該在渲染之外創建函數。例如:

RegistrationPage = React.createClass({ 
     render() { 
      return CreateFragment({ 
       email: <InputBlock 
        input={this.state.email} 
        onChange={this._onEmailChange}/>, 
       firstName: <InputBlock 
        input={this.state.firstName} 
        onChange={this._onFirstNameChange}/>, 
       ......... 
      }); 
     }, 

     _onFieldChange(key, event) { 
      //Save registered progress to store and re-render the component 
      AppActionCreators.saveRegisterProgress(this.state); 
     } 

     _onEmailChange() { 
      this._onFieldChange('email') 
     } 

     _onFirstNameChange() { 
      this._onFieldChange('firstName') 
     } 
    })