首页 > 解决方案 > 状态已更改但视图未更新 React Native

问题描述

我正在使用。'react-native-calendars'我的目标是显示点,然后在用户按下时标记多个日期。标记点是成功的。我使用markedDates对象作为状态变量,但是当更新markedDates对象以添加'selected':true, 'marked':true属性时calendar没有呈现它,我检查了markedDates对象,一切似乎都很好。

下面是代码

<Calendar style={{width:'100%',height:300}}
                  markingType={'multi-dot'}
                  onDayPress={(day) => {
                   this.handleConfirm2(day);
                  }}
                  markedDates={this.state.markedDates}
            />

下面的handleConfirm2方法

var calanderObj = this.state.markedDates;
    
      let o = calanderObj ['2021-09-02'];// adding properties to this spec date for testing
      o['selected'] = true;
      o['mark'] = true;

      calanderObj['2021-09-02'] = o;
      
      this.setState({markedDates:calanderObj},function (){
         console.log("after, state changed but calendar not displaing ",this.state.markedDates);
      });

标签: javascriptreact-nativereact-native-calendars

解决方案


试试这种方式(更新)

  /* This will create the clone of the object with a new ref, 
     so whenever the ref is updated, the view reflects */

  const calanderObj = {...this.state.markedDates};
    
  let o = calanderObj ['2021-09-02'];// adding properties to this spec date for testing
  o['selected'] = true;
  o['mark'] = true;

  calanderObj['2021-09-02'] = o;
  
  this.setState({markedDates:calanderObj},function (){
     console.log("after, state changed but calendar not displaing ",this.state.markedDates);
  });

推荐阅读