PureRenderMixin&国家管理设计

时间:2015-10-13 10:14:04

标签: javascript reactjs mixins

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

问题: 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 个答案:

答案 0 :(得分: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')
        }
    })