首页 > 解决方案 > 组件上的回调函数向 Redux 分派一个操作,但收到警告不要这样做

问题描述

我正在创建一个本质上是日期列表的日历。当你滚动日历时,selectedDate我的状态会通过 Redux 更新,使用回调函数调用 prop onDateDidChange

然后,我通过将日期与当前存储在状态中的日期进行比较来检查日期是否确实发生了变化,如果不同,我将发送我的操作以更新所选日期(日历列表顶部的日期)。

以下是相关代码:

class Calendar extends React.Component {

  onDateDidChange = date => {
    if (!isSameDay(this.props.selectedDate, date)) {
      this.props.onDateDidChange(date)
    }
  }

  render() {
    return (
      <VirtualList
        // other props...
        onItemsRendered={indexes => this.onDateDidChange(dateForIndex(indexes.startIndex))}
      /> 
    )
  }
}

Calendar.propTypes = {
  onDateDidChange: PropTypes.func,
  selectedDate: PropTypes.instanceOf(Date),
}

const mapStateToProps = createStructuredSelector({
  selectedDate: makeSelectSelectedDate(),
})

function mapDispatchToProps(dispatch) {
  return {
    onDateDidChange: date => dispatch(updateSelectedDate(date)),
  }
}

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
)

export default compose(withConnect)(Calendar)

这实际上有效,因为selectedDate当我滚动列表时在状态中更新,并且在将其映射到它们的道具的其他组件中更新它。问题是我收到以下关于在渲染期间更新状态/道具的警告:

warning.js:33 Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount

我使用react-tiny-virtual-list作为我的列表,特别是我使用它的onItemsRendered回调道具来获取列表的当前索引(“ selectedDay”)。如何使用此回调函数而不会导致此错误?

标签: javascriptreactjsreduxreact-redux

解决方案


推荐阅读