重新渲染时React应用程序崩溃

时间:2017-09-15 11:44:08

标签: javascript reactjs redux

我的react,redux应用程序中有多个路由,当导航到新路由时,一切正常,但是当我刷新页面时它会崩溃,因为它会尝试使用尚未提取的数据: 这是我的减速机里面的)

export const getDoorById = (reduxStore, door) => {
  console.log(reduxStore.fetchDoors.doors) // Nothing here
  return reduxStore.fetchDoors.doors.find(item => item._id == door)
}

所以我尝试在我的所有组件周围制作一个“LoadingWrapper”:

export default class LoadingWrapper extends Component {
  render() {
    if (this.props.isLoading) {
      return <CircularProgress />
    } else {
      return this.props.children
    }
  }
}

它适用于实际调度isLoading = true的组件,如下所示:

export function fetchEvents(state = initialState, action) {
  switch (action.type) {
    // CUSTOMERS
    case 'FETCH_CUSTOMERS':
      return { ...state, isLoading: true }

但是在一些其他组件减速器(它们完全相同)上它不起作用并且没有显示加载图标。所以一切都搞砸了。

我只是想知道如何解决这个让我无法刷新页面的烦人错误。

编辑:

这是我的减速机:

const initialState = {
  isLoading: false
}

export function fetchDoors(state = initialState, action) {
  switch (action.type) {
    case 'FETCH_DOORS':
      return { ...state, isLoading: true }

    case 'FETCH_DOORS_SUCCESS':
      return { ...state, doors: action.payload.setDoors, isLoading: false }

    case 'FETCH_CONTROLLERS':
      return { ...state, isLoading: true }

    case 'FETCH_CONTROLLERS_SUCCESS':
      return {
        ...state,
        controllers: action.payload.setControllers,
        isLoading: false
      }

    default:
      return state
  }
}

// This tries to get the array of 'doors'
export const getDoorById = (reduxStore, door) => {
  return reduxStore.fetchDoors.doors.find(item => item._id == door)
}

export const getControllerById = (reduxStore, controllerId) => {
  return reduxStore.fetchDoors.controllers.find(
    item => item._id == controllerId
  )
}

1 个答案:

答案 0 :(得分:0)

render() {
  if(!this.props.children && !isLoading) return null;

 if (this.props.isLoading) {
   return <CircularProgress />
 } else {
   return this.props.children
 }
}