问题
I'm wondering if you could help me fix the following issue. Using the native-base datepicker I am trying to manipulate the default date. On load from the parent component I am setting it to today's date. Then using some logic to add x number of months. The date is then updated in the state, but it's not being mapped to the datepicker. See code below:
// 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>
回答1:
This is pretty common (:
this.setState()
is async
so you will need to return a promise from this.setState()
to a function which will update your DatePicker
instead of just logging them. Then you can call forceupdate()
to show your updates.
if you were using stateless functional components, it will be much better as you would only need a simple Hook
to get all the above done.
keep in mind from docs:
Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().
来源:https://stackoverflow.com/questions/62147922/react-native-native-base-datepicker-issue