React-native原生基数据选取器问题。

问题描述 投票:0回答:1

我想知道你是否能帮助我解决以下问题。使用native-base datepicker,我试图操纵默认的日期,从父组件加载时,我将它设置为今天的日期。在从父组件加载时,我将它设置为今天的日期。然后使用一些逻辑来添加x个月数。然后在状态中更新日期,但它没有被映射到datepicker。请看下面的代码。

// 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>
react-native native-base
1个回答
1
投票

这是很常见的(:

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

如果你使用的是无状态的功能组件,那就会好很多,因为你只需要一个简单的 Hook 来完成上述所有工作。

从文档中可以看出,你应该避免使用forceUpdate()。

通常你应该尽量避免使用forceUpdate() 只在render()中读取this.props和this.state。

© www.soinside.com 2019 - 2024. All rights reserved.