在 mapStateToProps 中使用三元
Using ternary in mapStateToProps
好的,我们刚刚开始使用 Redux 和 Sagas,并使用它从服务器获取一些异步数据(JsonSchema)。
获取后,状态树如下所示:
{
"forms": {
"form-url": {
"isLoading": false,
"schema": { ... }
}
}
}
reducer 大概长这样:
const reducer = (state = {}, action) => {
switch (action.type) {
case FETCH:
const form = {};
form[action.url] = {
isFetching: true,
schema: {},
};
return Object.assign({}, state, form);
case FETCH_SUCCESS:
const sform = {};
sform[action.url] = {
isFetching: false,
schema: action.schema,
};
return Object.assign({}, state, sform);
}
return state;
}
现在,当将状态映射到道具时,数据还没有被获取,我们需要一个三元来让它工作:
const mapStateToProps = (state, ownProps) => {
return {
schema: state.forms[ownProps.sourceUrl] ? state.forms[ownProps.sourceUrl].schema : {}
}
}
尽管这有效,但我敏锐的直觉告诉我这是一种代码味道。是否有建议的模式来解决丢失的初始状态?
是的,您可以使用 reselect 来做到这一点,它更干净且可重复使用
好的,我们刚刚开始使用 Redux 和 Sagas,并使用它从服务器获取一些异步数据(JsonSchema)。
获取后,状态树如下所示:
{
"forms": {
"form-url": {
"isLoading": false,
"schema": { ... }
}
}
}
reducer 大概长这样:
const reducer = (state = {}, action) => {
switch (action.type) {
case FETCH:
const form = {};
form[action.url] = {
isFetching: true,
schema: {},
};
return Object.assign({}, state, form);
case FETCH_SUCCESS:
const sform = {};
sform[action.url] = {
isFetching: false,
schema: action.schema,
};
return Object.assign({}, state, sform);
}
return state;
}
现在,当将状态映射到道具时,数据还没有被获取,我们需要一个三元来让它工作:
const mapStateToProps = (state, ownProps) => {
return {
schema: state.forms[ownProps.sourceUrl] ? state.forms[ownProps.sourceUrl].schema : {}
}
}
尽管这有效,但我敏锐的直觉告诉我这是一种代码味道。是否有建议的模式来解决丢失的初始状态?
是的,您可以使用 reselect 来做到这一点,它更干净且可重复使用