gpt4 book ai didi

javascript - PureRenderMixin & 状态管理设计

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:29:53 25 4
gpt4 key购买 nike

我有一些带有状态的顶级组件 (RegisrationPage),它将状态/ Prop 传递给转储底层组件 (InputField, Dropdown日期选择器)。底层组件在回调的帮助下更改 RegistrationPage 的状态。

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

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

我们用代码来解释一下:

输入 block :

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)。

最佳答案

问题是 .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')
}
})

关于javascript - PureRenderMixin & 状态管理设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33100019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com