【问题标题】:How to get the value of state inside the function in React JS如何在 React JS 中获取函数内部的状态值
【发布时间】:2021-04-15 23:20:33
【问题描述】:

我现在有一个问题,状态不能在我的函数内部访问,所以错误类型是:无法读取未定义的 start_date 的属性。我有需要过滤的模块根据选择的日期范围。现在我有父子组件,我将选定的范围发送给孩子。现在在我的孩子内部,我将道具选择范围设置为我的状态。当我尝试控制台记录状态时,它说 start_date 未定义。我将向你们展示我的父组件和我的子组件。

错误:

无法读取未定义的 start_date 的属性

父组件:

<Grap  selected_range={this.state.selectionRange}/>

子组件:

this.state = {
            start_date:''
}

dataDate = () => {

    

        var date = new Date(), y = date.getFullYear(), m = date.getMonth();
    
        var firstDay = new Date(y, m, 1);
    
        var lastDay = new Date(y, m + 1, 0);
        
        var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    
        var dDate = []
    

        var startDate = this.state.start_date.startDate;
        

        var now = new Date();
        for (var d = new Date(startDate); d <= now; d.setDate(d.getDate() + 1)) {
            var date = new Date(d);
            let formatted_date = month[date.getMonth()] + " " + date.getDate();
            dDate.push(formatted_date);
        }
       
        return dDate
    
    }

    componentDidMount() {
        
        this.setState({
            start_date:this.props.selected_range
        })


    }

componentDidUpdate(prevProps) {
        if(this.state.start_date !== this.props.selected_range) {
           
            this.setState({
                start_date: this.props.selected_range
            })
        }        
    }

我在对象内部调用dataDate函数:

data = {

    labels: this.dataDate(),
    datasets: [
       
        {

            label: 'Receive Check',
            backgroundColor: 'rgb(195 218 251 / 35%)',
            borderColor: '#70a8f3',
            pointBackgroundColor: "#fff",
            pointBorderWidth: '2',
            fill: true,
            lineTension: 0.0,
            pointRadius: 7,
            borderWidth: 1,
            data: this.randomVal(),
        }
    ]
};

开始日期值:

【问题讨论】:

  • 函数在哪里调用?
  • @BrianThompson 嗨,我更新了我的内容。

标签: reactjs


【解决方案1】:
In your children component, 
this.state = {
            start_date:''
}

type of start date is string. You can't access property on string.
Define it something like this.state = {
            start_date: {}
}

【讨论】:

    【解决方案2】:

    this.state.start_date 以我们从 prop 收到的相同形式声明。

    
    this.state = {
      start_date: {
        endDate : new Date(),
        startDate : new Date(),
        key : ''
      
      }
      
    }
    
    

    之所以这样做,是因为react see ''在第一次挂载之前,导致报错。 你最好再看看lifecycle。 并使用moment 库来帮助您处理日期格式。

    【讨论】:

    • 即使我这样格式化,我也不能在函数内部调用状态
    • 如果您想要更好的答案,请更多代码行
    猜你喜欢
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多