React-native-native-base datepicker 问题 [英] React-native native-base datepicker issue
问题描述
我想知道您是否可以帮我解决以下问题.使用基于本机的日期选择器,我试图操纵默认日期.从父组件加载时,我将其设置为今天的日期.然后使用一些逻辑来添加 x 个月数.然后在状态中更新日期,但它没有被映射到日期选择器.见下面的代码:
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>
推荐答案
这很常见 (:
this.setState()
是 async
所以你需要从 this.setState()
返回一个 promise 到一个函数更新您的 DatePicker
而不是仅仅记录它们.然后你可以调用 forceupdate()
来显示你的更新.
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.
如果您使用的是无状态功能组件,那就更好了,因为您只需要一个简单的 Hook
即可完成上述所有操作.
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.
记住文档:
通常你应该尽量避免使用 forceUpdate() 并且只使用在 render() 中从 this.props 和 this.state 读取.
Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().
这篇关于React-native-native-base datepicker 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!