![](/img/trans.png)
[英]Print value from props, which is delivered to the component from redux by mapStateToProps
[英]Set local state of component with Redux props given from mapStateToProps()
我有一个输入值列表,我需要用调度函数返回的信息来填充...我无法在componentWillMount内设置状态,因为我需要等待reducer将信息返回至该状态。
内部componentWillMount方法分派调用以获取数据
componentWillMount() {
this.props.getData(this.props.params.id);
}
在componentWillReceiveProps方法内部,我使用作为数据返回的道具设置了本地状态,然后将setState()代码放入此方法中,以确保在connect()将数据合并到本地道具之后执行。 (还有更好的地方吗?)
componentWillReceiveProps(nextProps) {
if (nextProps.data) {
this.setState({
contact: nextProps.data.contact,
number: nextProps.data.number,
date: nextProps.data.date,
payment: nextProps.data.payment,
fields: nextProps.data.fields
});
}
}
然后渲染字段,使它们成为值状态
renderInputFields() {
if (this.state.fields) {
return this.state.fields.map(function(field, index) {
return (
<div key={'line-' + index}>
<input key={'quantity-' + index}
type="text"
id={index}
name="quantity"
placeholder="Add quantity"
value={field.quantity}
onChange={this.onFieldChange} />
<input key={'description-' + index}
type="text"
id={index}
name="description"
placeholder="Add description"
value={field.description}
onChange={this.onFieldChange} />
<input key={'price-' + index}
type="text"
id={index}
name="price"
placeholder="Add price"
value={field.price}
onChange={this.onFieldChange} />
<a onClick={this.onAddField}>
<i className="fa fa-times" aria-hidden="true"></i>
</a>
</div>
)
}, this);
}
}
const mapStateToProps = (state) => {
return {
data: state.data.selected
}
}
export default connect(mapStateToProps, { getData, updateDate, genData, deleteData })(DataEditor);
现在的问题是:
这是获得所需结果的一种好习惯吗?
使用Redux,您应该默认使用无状态组件。 无论是否使用redux,从props复制状态都是一种反模式,但这绝对不是您要使用redux要做的事情。
似乎拥有无状态组件似乎效率很低-尤其是对于像您在此处那样的输入字段。 但事实并非如此。 虚拟DOM将确保输入字段中的击键操作最终不会对DOM产生任何影响(因为它已经同步)。
同样,使用Redux,通常不会启动来自componentWillMount的Ajax请求。 通常,您在适当的时间调度操作(应用启动,或者如果您使用react-router,则为路由输入事件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.