遍历数组修改某一个值map
checkAll = () => {
const {todos} = this.state
const newTodo = todos.map((todo) => {
return {...todo, done: true}
})
this.setState({todos: newTodo})
}
遍历数组,筛选某一个值,进行统计操作reduce
const doneCount = todos.reduce((pre,todo)=>{
return pre + (todo.done ? 1 : 0)
},0)
遍历数组,进行筛选filter
clearAll = () =>{
const {todos} = this.state
const newTodos = todos.filter((todoObj)=>{
return !todoObj.done
})
this.setState({todos: newTodos})
}
React Ajax
-
添加axios
npm add axios
-
编写请求
getStudentInfo = () => { axois.get("http://localhost:9999/emp/list").then((data) => { const arr = data.data.data // console.log(arr) this.setState({employees: [...arr]}) }) }
-
解决跨域问题
-
配置代理(方法一)在packeg.json中追加以下代码
"proxy": "http://localhost:9999"
请求地址改为当前前端端口
getStudentInfo = () => { axois.get("http://localhost:3000/emp/list").then((data) => { const arr = data.data.data // console.log(arr) this.setState({employees: [...arr]}) }) }
-
-
兄弟组件中通信(消息发布与订阅)
1.下载PubSubJs npm add pubsub-js 2.引入组件
improt PubSub from 'pubsub-js'
3.谁接收消息,谁就订阅
componentDidMount() { //订阅· this.token = PubSub.subscribe('atguigu',(_,data)=>{ //atguigu是消息名称,用作标识, //谁发布名为atguigu的消息,就会触发回调函数 console.log(data) }) } componentWillUnmount() { //组件即将被卸载时,取消消息订阅 PubSub.unsubscribe(this.token) }
4.谁发送消息,谁就发布
sendInfo = () =>{ //发布 PubSub.publish('atguigu',{name:'张三',age:18,gender:'男'}) }
-
父子之间传东西props
<Item xxx={this.xxx}/>