【发布时间】:2020-05-11 07:25:29
【问题描述】:
我在一个名为 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;
在控制台上
【问题讨论】:
-
查看反应生命周期。
-
你能不能在codesandbox.io上创建一个codesandbox并分享一下,这样调试起来会更方便。
标签: javascript reactjs