我在 Redux 中遇到异步操作问题。
错误:Cannot read property 'map' of undefined Map: 71
问题是 MapContainer 组件在 aysnc device
响应之前尝试挂载action 已经添加到 Redux store。所以this.props.device
未定义,我无法在其上调用 map 。但是我需要为此做一些事情来获取 MapContainer 组件中的数据。
我最初尝试解决这个问题是移动 this.props.dispatch(setDevice())
来自 componentWillMount()
MapContainer 组件的 componentWillMount()
父 App 组件。
基本上我需要想办法得到 this.props.device
在安装 MapContainer 组件时或至少在 interpenetrate 位于 render()
时拥有正确的数据MapContainer 组件尝试解析 this.props.device.sessions.map
时的方法.
任何方向将不胜感激。这是人们使用 RxJS observable 来解决的事情吗?有没有一种无需添加新工具即可解决此问题的简单方法?
组件/Map.js:
<LayersControl position='topright'>
{console.log('#########this.props', this.props)}
{
this.props.device.sessions.map((session, i) => {
return (
<Overlay name={String(i + 1)} key={i}>
<Polyline color='red' positions={session.waypoints} />
</Overlay>
)
})
}
</LayersControl>
组件/App.js:
componentWillMount() {
//console.log('this.props', this.props)
console.log('dispatch setDevice')
this.props.dispatch(setDevice())
}
actions/device.js:
export function setDevice(data) {
console.log('in setDevice action')
return {
type: 'SET_DEVICE',
payload: fetch('/click')
.then(resp => resp.json())
.then(data => {
console.log('in second then of fetch')
return data
})
.catch(err => console.error(err))
}
}
reducers/device.js:
export default function reducer(state = {
device: ''
}, action) {
switch (action.type){
case 'SET_DEVICE':
console.log('in reducer SET_DEVICE case')
return {...state, data: action.payload, device: action.payload[0] }
default:
console.log('in reducer DEFAULT case')
return state
}
}
最佳答案
您可以添加一个条件来检查 this.props.device.session
是否未定义,
<LayersControl position='topright'>
{console.log('#########this.props', this.props)}
{
this.props.device.sessions && this.props.device.sessions.map((session, i) => {
return (
<Overlay name={String(i + 1)} key={i}>
<Polyline color='red' positions={session.waypoints} />
</Overlay>
)
})
}
</LayersControl>
或者您可以将 data.sessions
初始化为一个空数组,并在来自异步操作的数据返回时覆盖它。
关于javascript - 异步操作未及时将数据添加到 Redux 存储导致错误 : Cannot read property 'map' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43358868/