React Native: Possible UNhandled Promise Rejection: Can't find variable: name

时间:2017-07-12 08:22:27

标签: javascript reactjs react-native

While trying to make an app that would ask for 3 dates, i've stumbled on a problem :

I have this:

onDateChange = (state) => (event, value) => {
    this.setState({
        [state]: name
    });
}

that is called by:

<DatePicker
    dateMes={this.state.dateMes}
    mode="date"
    placeholder="select date"
    format="DD-MM-YYYY"
    minDate="01-01-1950"
    maxDate="01-01-2050"
    androidMode="spinner"
    showIcon={false}
    onDateChange={this.onDateChange('dateMes')}
/>

When loaded, my 3 datepickers are juste filled with the placeholder. When i open them and select a date, nothing will change (as if i never selected a date)

I believe it's not finding how to make the onDateChange work, but I don't know how to make it work

Thanks for the help !

EDIT: Thanks to Chris G, i got a solution. My function now looks like

onDateChange = (state) => (event, name) => {
    this.setState({
        [state]: name
    });
}

The error disappeared, but the date are not changed with the datepicker.

3 个答案:

答案 0 :(得分:1)

让我给出一些观点,OnDateChange prop接收一个函数,它充当你正在分配它的回调,但是当调用回调时,'this'的引用已经改变,它无法找到由班级

现在,在本机示例中,他们使用了箭头函数,它在词法上限制了“this”的范围,这解释了为什么你可以找到类变量,因为'this'仍然指代组件。 参考:Arrow Functions

答案 1 :(得分:0)

我实际上只需要继续使用DatePicker官方的github。他们有一个例子,他们做了类似的事情:

<DatePicker
    date={this.state.dateMes}  //it was dateMes=..., wich just meant nothing
    mode="date"
    placeholder="select date"
    format="DD-MM-YYYY"
    minDate="01-01-1950"
    maxDate="01-01-2050"
    androidMode="spinner"
    showIcon={false}
    onDateChange={(dateMes) => { this.setState({ dateMes: dateMes }); }}
/>

没有任何功能或其他

而且,它有效。这就是全部:)。

答案 2 :(得分:0)

完成setState之后,必须在构造函数中明确定义它。尝试此操作

<DatePicker
date={this.state.dateMes}  //it was dateMes=..., wich just meant nothing
mode="date"
placeholder="select date"
format="DD-MM-YYYY"
minDate="01-01-1950"
maxDate="01-01-2050"
androidMode="spinner"
showIcon={false}
 onDateChange={(date) => {this.setState({date: date})}}/>

constructor(props) {
    super(props);
  this.state = {
                date:''

  };
}