代码之家  ›  专栏  ›  技术社区  ›  stone rock

如何在reactjs中的道具上使用reduce()?

  •  0
  • stone rock  · 技术社区  · 6 年前

    我制作了一个父组件和子组件(piechart.js)。我将道具从父组件传递到piechart组件,如下所示->

     <Pie batdata={this.props.BattingRecord}/>
    

    上面的代码在父组件中。现在我想从piechart组件(它是子组件)中的道具中提取数据。

    当我在piechart组件构造函数中尝试console.log(this.props)时,它会在控制台中显示json数据。见以下截图:

    enter image description here

    现在我想得到 how 内部参数 dismissal 请看上面的截图。我想我没有正确使用道具。所以我在piechart组件中的尝试如下:

    piechart.jsx文件:

      import React, { Component } from 'react';
    
        const wickets = this.props.batdata.reduce( (a,{dismissal})  =>{  <--Getting error at this line
            if(!a[dismissal.how]){
                a[dismissal.how]=1;
            }else{
                a[dismissal.how]=a[dismissal.how] + 1;
            }
            return a; 
        }, {});
    
    
        console.log(wickets);
    
        const dismissals = Object.values(wickets);   
    
        const labels = Object.keys(wickets);  
    
        //console.log(dismissals);
    
        //console.log(labels);
    
    class Pie extends Component {
    
      constructor(props){
        super(props);
        console.log(this.props)
      }
    
      componentDidMount(){
        const piechart = new Chartist.Pie('.ct-pie-chart', data, options, responsiveOptions);
      }
    
      render(){
        return(
          <div>
              <div className="col-md-3 col-xs-6 ct-pie-chart">
                  {this.piechart}
              </div>
          </div>
    
        )}
    
    }
    
    export default Pie ;
    

    对于上面的代码,我得到类型错误: TypeError: Cannot read property 'batdata' of undefined

    2 回复  |  直到 6 年前
        1
  •  2
  •   Code-Apprentice    6 年前

    问题是 const wickets 在扩展的类之外分配 Component . 您需要将此代码移动到 class Pie . this.props 只在扩展的类中定义 成分 .

    class Pie extends Component {
        ...
        componentDidMount(){
            const wickets = this.props.batdata.reduce( (a,{dismissal})  =>{
                if(!a[dismissal.how]){
                    a[dismissal.how]=1;
                }else{
                    a[dismissal.how]=a[dismissal.how] + 1;
                }
                return a; 
            }, {});
            // Now you can use the value of "wickets" however you wish in this function
    
        this.piechart = new Chartist.Pie('.ct-pie-chart', data, options, responsiveOptions);
    }
    

    即使在解决了这个问题之后,您也可能会遇到正在使用的饼图库的其他问题。如果它打算在react应用程序中使用,那么您没有以正确的方式呈现它。

        2
  •  1
  •   Thai Duong Tran    6 年前

    问题在于 Piechart 组件。这个错误是很自我解释的,你的 this.props 未定义。没有 皮埃图 组件的代码,确切的问题无法说明,但是,有两个常见错误可能导致此错误:

    • 您试图访问未正确绑定或

    • 你正在尝试访问 这道具 在无状态功能组件中,或

    • 在组件的构造函数中 super(props) 被称为。

    编辑:您正在访问 这道具 我们这边有个合适的背景,你可能想知道 this 先在JS工作: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/ .

    要更正组件,可以将reduce函数移到组件类中,也可以将其放入 componentDidMount 方法。