【问题标题】:Component crashes when re-render | React, Redux重新渲染时组件崩溃 |反应,还原
【发布时间】:2017-09-14 20:29:17
【问题描述】:

我有一个奇怪的问题,当我重新渲染组件时,我的 react、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
)

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

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

【问题讨论】:

  • 您需要调查为什么reduxStore.fetchDoors.doorsnull。插入console.log(reduxStore.fetchDoors); 可能会提供线索。
  • 我试过你的类型,我唯一得到的是isLoading: false,我想这是因为我的initialState在我的减速器中为fetchDoors

标签: javascript reactjs redux async-await


【解决方案1】:

您首先需要通过对您的对象进行空检查来解决崩溃问题 "reduxStore.fetchDoors.doors"

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

下一步是找出为什么你的对象“reduxStore.fetchDoors”是空的。 如果我是你,我会先去你的 Reducer 并排查你的 store 状态是否被某处覆盖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2022-11-07
    • 2020-03-08
    • 2018-12-27
    • 2018-09-19
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多