【发布时间】:2020-10-17 22:40:03
【问题描述】:
我需要您对使用选择器过滤数据的建议。假设我的应用程序中有以下实体。 1 个组织有多个设备,在我的状态下看起来如下:
state {
devices: {
byId: [ 1 { name: device1 } ]
}
organizations: {
byId: [
1 { name: org1, devices: [1,2,3] }
]
}
}
现在我想过滤组织内的设备。这是我想用选择器做的事情。我的选择器如下所示:
const selectDevice = (id: any) => (state: State) => state.devices.byId[id]
export const selectOrganizationDevices = (id: number) => (state: State) => {
const organization = state.organizations.byId[id] || []
return organization.devices.map(id => selectDevice(id)(state))
}
这应该可以正常工作,但是在我从 redux 发送数据之前,我的选择器就被调用了。我想我的减速器或我创建的组件有问题。
我的减速器是这样的:
return produce(state, draftState => {
switch (action.type) {
...
case OrganizationActionTypes.FETCH_DEVICES_SUCCESS: {
draftState.byId = action.payload.entities.organizations
draftState.allIds = Object.keys(action.payload.entities.organizations)
draftState.loading = false
break;
}
...
default: {
return state
}
}
})
我的功能组件如下所示:
function Devices() {
const dispatch = useDispatch();
const devices = useSelector(selectOrganizationDevices(1))
useEffect(() => {
dispatch(fetchOrganizationDevices(1))
}, [])
const columns = []
return (
<Layout headerName={"Devices"}>
<Table dataSource={devices} columns={columns}/>
</Layout>
)
}
我现在得到的错误是organization.devices is undefined,它表示处于状态的设备数组为空。似乎在调度之前调用了 useSelector 。如何防止 redux 这样做?或者我的代码应该改变什么?
【问题讨论】:
-
试试
return organization.devices ? organization.devices.map(id => selectDevice(id)(state)): []
标签: reactjs redux react-hooks