初入前端4.20日总结


2.想要改变数组中的值,不能直接赋值变量,需要用数组的方式, 数组名.属性名 = ''        给存在的数组名重新赋值,这样才能更新数组内的内容
3.当绑定点击事件时,需要.bind(this),才能保持this的指向,使用箭头函数就不用.bind(this)
// 绑定this
this.decrease   =   this.decrease. bind( this);
4.如果绑定的事件中需要传参的话,要这样写onClick={()=>this.handleClick(index)}        示例如下
< div   className = "decrease crease"   onClick = {() => this. decrease(index) }>-</ div>
5.如果循环遍历的值,需要单独操作,如 购物车商品的个数count,不要给全局的变量,给循环遍历的数组中各自添加局部的属性来显示个数(单独控制),如循环遍历后的item.count,可以用 this.state.数组来修改count值从而改变个数(前提是这个数组已经在this.state中初始化了,才可以使用this.setState)改变数据中的count来达到改变购物车商品的数量,单独控制,不需要全局,否则全部商品一起同步修改
constructor( props) {
super(props);
this.state   =  {
// count: 0, //设置默认初始值为1,不要设置全局的,全局的一改变,其他地方就会改变
goodsData:[
{img:   "../images/cafe1.jpg",title: "意式咖啡豆",type: "默认",money: "65",count:   0},
{img:   "../images/cafe1.jpg",title: "意式咖啡豆",type: "默认",money: "65",count:   0},
{img:   "../images/cafe1.jpg",title: "意式咖啡豆",type: "默认",money: "65",count:   0},
{img:   "../images/cafe1.jpg",title: "意式咖啡豆",type: "默认",money: "65",count:   0},
{img:   "../images/cafe1.jpg",title: "意式咖啡豆",type: "默认",money: "65",count:   0},
{img:   "../images/cafe1.jpg",title: "意式咖啡豆",type: "默认",money: "65",count:   0},
{img:   "../images/cafe1.jpg",title: "意式咖啡豆",type: "默认",money: "65",count:   0},
{img:   "../images/cafe1.jpg",title: "意式咖啡豆",type: "默认",money: "65",count:   0},
],
totalSum:   '',   //定义总额
}


-------------------------------------------------------------------------------------------------
// 点击减少数字
decrease( index){

//把数组中的count值-1赋值给数组中的count
this.state.goodsData[index].count   =   this.state.goodsData[index].count - 1
if( this.state.goodsData[index].count   <   0){
this.state.goodsData[index].count   =   0;
}
this. setState({
//更新数组一起更新数组中的属性
goodsData: this.state.goodsData
})
}

6.   +=  既可以连接字符串还可以连接数字,如果想要数字相加,就要转化数字,如Number()
sum   +=   Number( this.state.goodsData[i].money);
7.想要获取到数组中的索引值,需要先遍历数组来获取
for( let  i   =   0;  i   <   this.state.goodsData.length;  i ++){console.log(i)}


猜你喜欢

转载自blog.csdn.net/qq_32007439/article/details/80024239