PureRenderMixin & 状态管理设计

PureRenderMixin & state management design

我有一些带状态的顶级组件 (RegisrationPage),它将它传递 state/props 以转储底层组件 (InputFieldDropdownDatepicker). 底层组件在回调的帮助下改变 RegistrationPage 的状态。

问题: PureRenderMixin 不起作用,因为我必须绑定传递给底层组件的状态更改回调.

问题: 如何让PureRenderMixin以最优雅的方式工作?

我们用代码来解释一下:

输入块:

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 = 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 作为额外的 属性 传递并在底层组件中进行绑定。

问题是 .bind() returns 每次调用它时都会出现一个新函数。为避免这种情况,您应该在渲染之外创建函数。例如:

    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')
        }
    })