javascript - 组件上的回调函数向 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
”)。如何使用此回调函数而不会导致此错误?
解决方案
推荐阅读
- python - 如何检测 OpenCV 中何时释放密钥?
- javascript - 引导切换按钮在 reactjs 中不起作用
- vue.js - 将导航栏品牌的一部分放在栏外
- structure - systemverilog 中的通用结构
- hyperledger-sawtooth - 无法将 intkey Tp 连接到锯齿测试网络
- arduino - 使用 ArduinoJson 的 Arduino Nano 和 NodeMCU 之间的串行通信失败
- python - Pytorch 梯度计算
- android - BottomSheetDialogFragment 中的 NavigationComponent 导航
- python - 如何在python的循环内的socketio中发出事件?
- sql - 我必须使用 '/*' 才能显示备注吗?因为它不断收到错误