React Native修改markedDates后react-native-calendars视图未更新怎么办
问题原因
React的props更新触发重渲染依赖浅比较,你直接修改了state中已有的markedDates对象属性,没有生成新的对象引用,Calendar组件会判断markedDates未发生变化,因此不会重新渲染标记。同时你原代码中将标记属性写为mark,官方要求的属性名为marked,拼写错误也会导致标记不生效。
修复代码
修改handleConfirm2方法,拷贝生成新的状态对象再更新:
handleConfirm2(day) { // 生成新的markedDates对象,变更引用 const newMarkedDates = {...this.state.markedDates}; const targetDateKey = '2021-09-02'; // 拷贝目标日期的配置对象,新增属性 newMarkedDates[targetDateKey] = { ...newMarkedDates[targetDateKey], selected: true, marked: true }; this.setState({markedDates: newMarkedDates}, () => { console.log("状态更新完成,日历标记已同步", this.state.markedDates); }); }
补充说明
如果你的标记类型是multi-dot需要配置dots数组,修改时也要对dots数组做拷贝生成新数组,避免原引用修改导致的不渲染问题。
内容的提问来源于stack exchange,提问作者usmandroid
相关产品推荐
相关产品推荐

