0.避免无意义的父节点
import React from 'react';
const SecondsTop = ({title}) => [
<div className="top">
<i className="logo1"/>
</div>,
<div className="top">
这是{title}
</div>
];
export default SecondsTop;
1.优雅的渲染一个list
经常遇到的开发需求,从后台来到一个list数据,在前端展示出来
先手动造一个list数据
import React from 'react';
class Index extends React.Component{
constructor(props){
super(props);
this.state = {
list: [
{id:1, title:'测试1'},
{id:2, title:'测试2'},
{id:3, title:'测试3'},
{id:4, title:'测试4'},
{id:5, title:'测试5'},
{id:6, title:'测试6'},
]
};
}
handleItemDel(id){
//console.log(id)
let list = this.state.list;
list.splice(list.findIndex(data => data.id === id ), 1);
this.setState({list: list})
}
render(){
let {list} = this.state;
return(
<div>
{
list.map(data => <li key={data.id}>{data.title}
<button onClick={()=>this.handleItemDel(data.id)}>删除</button></li>)
}
</div>
)
}
}
2.如何处理List里面的Item(增删改查)
[见上面代码]
(1)删除:先增加一个删除按钮
(2)给按钮添加事件,绑定函数,并把id传参过去,点击删除按钮,看能否打印出当前id
(3)接下来写删除事件:(handleItemDel函数)
补充知识:
splice() 方法可删除从 index 处开始的零个或多个元素,并且用参数列表中声明的一个或多个值来替换那些被删除的元素。
语法:
arrayObject.splice(index,howmany,item1,.....,itemX)
【index:必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
howmany:必需。要删除的项目数量。如果设置为0,则不会删除项目。
itme1,...,itemX:可选。向数组添加的新项目。】
代码:http://www.w3school.com.cn/tiy/t.asp?f=jseg_splice
findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。
findIndex() 方法为数组中的每个元素都调用一次函数执行:
·当数组中的元素在测试条件时返回true时,findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
·如果没有符合条件的元素返回-1
注意:findIndex() 对于空数组,函数是不会执行的。findIndex() 并没有改变数组的原始值。