[英]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.