React-native native-base datepicker 问题

React-native native-base datepicker issue

我想知道你能否帮我解决以下问题。我正在尝试使用基于本机的日期选择器来操纵默认日期。从父组件加载时,我将其设置为今天的日期。然后使用一些逻辑来添加 x 月数。然后在状态中更新日期,但它没有映射到日期选择器。请参阅下面的代码:

// Parent state from parent component

state = {
  index: 0,
  routes: [
    { key: '1', title: 'STEP 1' },
    { key: '2', title: 'STEP 2' },
    { key: '3', title: 'STEP 3' },
    { key: '4', title: 'STEP 4' }
  ],
  purposes: [],
  purpose_Of_Examination_Id: 0,
  colours: [],
  colour_Id: 0,
  first_Examination: false,
  installed_Correctly: null,
  defect_Reason_Id: 0,
  defect_Reasons: [],
  hasDefects: false,
  defect: '',
  inspected_At: moment().toDate(),
  next_Inspection_Date: moment().toDate()
}

// Child component

constructor(props: any) {
  super(props);

  this.state = this.props.parentState;
}

async componentDidMount() {
  this.bindDates();
}

bindDates() {
  var inspected_At = moment().toDate();
  var next_Inspection_Date = moment().toDate();  
  var safe_For_Use = false;

  if (this.props.inspection.hasDefects == true) {
    next_Inspection_Date = moment().toDate();
    safe_For_Use = false;
  } else {
    next_Inspection_Date = moment(inspected_At).add(this.props.equip.inspection_Interval, 'M').toDate();
    safe_For_Use = true;
  }

  this.setState({inspected_At: inspected_At, next_Inspection_Date: next_Inspection_Date, safe_For_Use: safe_For_Use}, () => {
    console.log("NEXT INSPECTION DATE state: " + this.state.next_Inspection_Date);
  });
}

// Part of view

<View style={styles.nextInspectionDateContainer}>
  <View style={styles.inputContainer}>
    <Text style={styles.inputLabel}>Next Inspection Date:</Text>
    <DatePicker
    locale="en_GB"
    defaultDate={this.state.next_Inspection_Date}
    formatChosenDate={date => { return moment(date).format('DD/MM/YYYY'); }}
    onDateChange={(date) => { this.setState({ next_Inspection_Date: date }) }}
    />
  </View>
</View>

这很常见 (:

this.setState()async 所以你需要 return 从 this.setState() 到一个函数的承诺,它会更新你的 DatePicker 而不仅仅是记录他们。然后你可以调用 forceupdate() 来显示你的更新。

如果您使用的是无状态功能组件,那会好得多,因为您只需要一个简单的 Hook 即可完成上述所有操作。

请记住文档:

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().