重新渲染时组件崩溃React,Redux

时间:2017-09-14 10:33:26

标签: javascript reactjs redux async-await

我有一个奇怪的问题,当我重新渲染组件时,我的反应,redux应用程序崩溃了。我正在谈论的这个组件,DoorsSettingsContainer。它有自己的路径:

<AuthRoute
  exact
  path="/settings/:itemId"
  component={DoorsSettingsContainer}
/>

第一次通过链接导航到它时:

<Link to={{ pathname: `/settings/${door._id}` }}>
  <p className="sub-title-text-container">Inställningar</p>
</Link>

它工作正常,但当我在DoorsSettingsContainer并刷新我的页面时,一切都崩溃了。这是我的组件(我删除了我的导入以减少长度)。

// NOTE: There's no data here so my app crashes :-(
const getDoorById = (reduxStore, door) => {
  return reduxStore.fetchDoors.doors.find(item => item._id == door)
}

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

class DoorSettingsContainer extends Component {
  componentDidMount() {
    this.props.fetchDoors()
  }

  render() {
    const door = this.props.doors || []
    const controller = this.props.controllers || []
    if (this.props.isLoading) return <CircularProgress />
    return (
      <div>
        <DoorSettingsForm
          onSubmit={this.props.updateSettings}
          door={door}
          id={this.props.match.params}
          controller={controller}
        />
      </div>
    )
  }
}

DoorSettingsContainer.propTypes = {
  doors: PropTypes.object.isRequired,
  controllers: PropTypes.object.isRequired,
  fetchDoors: PropTypes.func.isRequired
}

const mapStateToProps = (state, ownProps) => {
  const door = getDoorById(state, ownProps.match.params.itemId)
  const doorId = ownProps.match.params.itemId
  const controller = getControllerById(state, door.controller)

  return {
    doors: door,
    controllers: controller,
    isLoading: state.settings.isLoading
  }
}

const mapDispatchToProps = dispatch => {
  return {
    fetchDoors: () => dispatch(fetchDoors()),
    updateSettings: (id, door, controller) =>
      dispatch(updateSettings(id, door, controller))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(
  DoorSettingsContainer
)

这是我的错误信息: enter image description here 我想我应该提到我正在使用异步等待我的行动fetchDoors,所以不是常规的承诺。我也读过这篇文章:Why is componentDidMount not being called when I re-render?但没有运气。

感谢阅读,希望我们可以一起解决这个问题。

1 个答案:

答案 0 :(得分:2)

首先需要通过对Object执行nullcheck来解决崩溃问题 &#34; reduxStore.fetchDoors.doors&#34;

const getDoorById = (reduxStore, door) => {
 return (!!reduxStore && !!reduxStore.fetchDoors) ? reduxStore.fetchDoors.doors.find(item => item._id == door) : null
}

下一步是找出你的对象&#34; reduxStore.fetchDoors&#34;是空的。 如果我是你,我会首先去你的Reducer,如果你的商店状态被某处覆盖,我会排除故障。