我的商店是下一个:
const initialState = {
all: {
"name": "",
"datas": {
"data1": {
"subdata1": [],
"subdata2": [],
},
"data2": {
"subdata1": [],
"subdata2": [],
},
}
}
}
我有下一个组件:
* All: main Component, map to Data with all.datas
* Data: show data1 or data2 or data3. map to Subdata with data1 and data2 ...
* Subdata: show list subdata1
我在subdata中有一个redux Connect,我希望还原器,而不是返回一般状态,返回一个subdata状态。
例如:
subdata.js:
class Subdata extends React.Component {
// ....
}
function mapStateToProps(state, ownProps) {
return {
subdata: ownProps.subdata
};
}
function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(Actions, dispatch) }
}
export default connect(mapStateToProps, mapDispatchToProps)(Subdata);
reducers.js:
const subdata = (state = {}, action) => {
// I want that state return: subdata, in this case, []
// instead of all: {...}
const copy = JSON.parse(JSON.stringify(state));
switch(action.type) {
case "ADD_SUBDATA":
// In this moment: I need pass a lot of vars: data_id and subdata_id
my_subdata = state.datas[data_id][subdata_id]
// I want get directly the subdata
my_subdata = state.subdata
default:
return state;
}
}
这可能吗?如何?
非常感谢您。
是的。
您可以考虑在还原器中使用 dot-prop-immutable
或immutable.js在商店的"切片"上选择性操作。
使用dotprop示例的伪代码:
// Getter
dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar')
签名:
get(object, path) --> value
我在您的代码中注意到您正在使用以下来"克隆"您的状态:
const copy = JSON.parse(JSON.stringify(state));
这并不是最佳的,因为您完全克隆了所有状态对象,而应仅在其一部分上操作(还原器运行的位置,特别是与合并的还原器一起工作(。