Async action not adding data to Redux store in time leading to, Error: Cannot read property 'map' of undefined

Async action not adding data to Redux store in time leading to, Error: Cannot read property 'map' of undefined

我在 Redux 中遇到异步操作问题。

错误:Cannot read property 'map' of undefined Map: 71

问题在于,在 aysnc device 操作的响应尚未添加到 Redux 存储之前,MapContainer 组件正在尝试安装。所以 this.props.device 是未定义的,我不能在上面调用 map 。但是我需要为此做一些事情来获取 MapContainer 组件中的数据。

我最初尝试解决这个问题是将 this.props.dispatch(setDevice()) 从 MapContainer 组件的 componentWillMount() 移动到父 App 组件的 componentWillMount()

基本上我需要想出一种方法让 this.props.device 在安装 MapContainer 组件时获得正确的数据,或者至少在 interpenetrate 处于 [=21= 时] MapContainer 组件尝试解析 this.props.device.sessions.map.

时的方法

任何方向将不胜感激。这是人们使用 RxJS observable 来解决的事情吗?有没有一种无需添加新工具即可解决此问题的简单方法?

components/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>

components/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 初始化为一个空数组,并在来自异步操作的数据返回时覆盖它。