环境:基于React脚手架的模板更改
目录:
单向数据流
代码:
src/App.js
import React,{Component} from "react";
import './App.css';
//map遍历数组
const list =[{
title:'React',
url:'https://facebook/github.io/react/',
author:'Jordan Walke',
num_comments:3,
points:4,
objectID:0,
},
{
title: 'Redux',
url:'https://github.com/reactjs/redux',
author:'Dan Abramov,Andrew Clark',
num_comments: 2,
points: 5,
objectID: 1,
}
];
class App extends Component{
constructor(props) {
super(props); //需要强制调用super(),因为App是Conmonent的子类
this.state = {
list: list,
};
//在构造函数中绑定onDismiss方法
this.onDismiss = this.onDismiss.bind(this);
}
onDismiss(id) {
// function isNotId(item){
// return item.objectID !== id;
// }
//上述代码的箭头函数写法
const isNotId = item => item.objectID !== id;
//filter函数:过滤某些元素返回剩下的元素
//此处过滤掉item.objectID == id的元素,返回item.objectID !== id的元素以实现删除某行数据的效果
//此函数返回的是一个新的列表,而不是改变旧列表.遵循React中不可变数据的约定。
const updatedList = this.state.list.filter(isNotId);
this.setState({list:updatedList})
}
render() {
return (
<div className="App">
{this.state.list.map(item =>
<div key={item.objectID}>