我不明白props如何在reactjs中工作

我已经在名为counter.jsx的模块中编写了一个组件计数器,现在我试图将该组件(计数器)导入新的模块counter .jsx中,并在counters.jsx中使用四次。现在,当我尝试在counters.jsx渲染方法中打印道具时,每个组件都会被打印两次。所以它在控制台上将道具对象打印了8次,共包含四个组件。为什么要打印8次,有人可以解释一下吗

counter.jsx

import React, { Component } from 'react';

class Counter extends Component {

    state = {count:0,
             tags : ['tag1','tag2','tag3'],
             tagObj : {'tag1':1 , 'tag2':2},
             id:5

    };

    //User-def Functions

    h=5;

    formatCount()
    {
        if(this.state.count === 0)
        {
            return 'Zero';
        }
        else
        {
            return this.state.count;
        }

    }

    // how to use map functions
    renderList()
    {
        const List = this.state.tags.map( (tag) =>  <li key={tag} > <a href='/'>{tag}</a> </li>  );
        return (List.length===0)?<p>shopping cart is empty</p>: List ;
    }


    getBadgeClassess()
    {
        var classes = 'badge m-2 badge-';
        classes += (this.state.count === 0) ? "warning" : "primary";
        return classes;
    }

     handleCountIncrement = () => {

        //  console.log(incr);
         this.setState( { count: this.state.count + 1 });
     }

    // Render Function
    render() { 

        console.log("props" , this.props);
        return(
                //  <React.Fragment>
                <div>                     
                    <span className={this.getBadgeClassess()}>{this.formatCount()}</span>
                    <button onClick={ this.handleCountIncrement  } className='btn btn-primary btn-sm' >Increment</button>

                     {/* <ul> */}
                        {/* { this.state.tags.map( tag => <li>{ tag }</li>) } */}
                        {/* {this.renderList()} */}
                     {/* </ul> */}

                </div>

                // </React.Fragment> 
              );


        }
}

export default Counter;

counters.jsx

import React, { Component } from 'react';
import Counter from './counter';


class Counters extends Component {
    state = { 
       counters : [ 
           { id:1 , value:0 },
           { id:2 , value:0 },
           { id:3 , value:0 },
           { id:4 , value:0 }
        ]
     }

    //  renderCounters = () =>{

    //  }


    render() { 

        console.log("props" , this.props);
        return ( 
            <div>

                {this.state.counters.map( (counter) => ( <Counter key={counter.id} selected={true} />) ) }

            </div>
         );
    }
}

export default Counters;

在控制台上

enter image description here

评论