反应本机本机数据库日期选择器问题



我想知道您是否可以帮助我解决以下问题。使用本机基础日期选择器,我正在尝试操作默认日期。从父组件加载时,我将其设置为今天的日期。然后使用一些逻辑来添加 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,因此您需要将this.setState()的承诺返回给一个函数,该函数将更新您的DatePicker,而不仅仅是记录它们。然后,您可以调用forceupdate()来显示您的更新。

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

请记住文档:

通常你应该尽量避免所有使用forceUpdate((,并且只 从 this.props 和 this.state in render(( 中读取。

最新更新