我试图简单地对mapStateToProps
中的redux商店数据进行排序,类似于在Dan Abramov的Egghead.io视频中进行的操作:https://egghead.io/lessons/javascript-redux-colocating-selectors-with-reducers
我的问题是,最初状态是返回undefined(因为它是异步获取的),那么处理这个问题的最佳方法是什么?当前代码如下(_
是ramda
库):
const diff = (a, b) => {
if (a.name < b.name) {
return -1
}
if (a.name > b.name) {
return 1
}
return 0
}
const mapStateToProps = (state) => {
return {
transactions: _.sort(diff, state.transactions.all),
expenditure: state.expenditure.all,
income: state.income.all
}
}
我认为transactions.all
最初应该是一个空数组(这意味着代码可以工作),因为在reducer中设置了初始状态:
const INITIAL_STATE = { transactions: { all: [] }, transaction: null }
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_TRANSACTION:
return { ...state, transaction: action.payload.data }
case FETCH_TRANSACTIONS:
return { ...state, all: action.payload.data }
case EDIT_TRANSACTION:
return { data: action.data }
case ADD_TRANSACTION:
return { data: action.data }
case DELETE_TRANSACTION:
return { ...state }
default:
return state
}
}
提前致谢。
答案 0 :(得分:1)
如你所说,它是异步获取的。也许当组件渲染时,数据尚未准备就绪,导致未定义的对象。
const SampleComponent = (props) => {
if(props.transaction === undefined)
return <Spinner /> // Loading state
else
// your implementation
}
您可以在此处的文档中进一步使代码更清洁,如Dan自己所解释的:http://redux.js.org/docs/advanced/AsyncActions.html
答案 1 :(得分:0)
管理来解决这个问题,因为在组合reducers中,我设置了名为transactions
的事务,然后在reducer中,我基本上将初始状态设置为transactions: { all: [] } }
。
这导致state.transactions.all
未定义,因为正确的状态结构实际上是state.transactions.transactions.all
。
将交易减速器更新为:
const INITIAL_STATE = { all: [], transaction: null }
export default function (state = INITIAL_STATE, action) {
switch (action.type) {...
在promise返回之前的初始空事务数组意味着排序不再导致错误,然后在加载时正确排序。