React常用,数组遍历、过滤、筛选,axios,消息发布与订阅(一)

遍历数组修改某一个值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

  1. 添加axios

    npm add axios
  2. 编写请求

    getStudentInfo = () => {
        axois.get("http://localhost:9999/emp/list").then((data) => {
            const arr = data.data.data
            // console.log(arr)
            this.setState({employees: [...arr]})
        })
    }
  3. 解决跨域问题

    • 配置代理(方法一)在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]})
        })
    }
  4. 兄弟组件中通信(消息发布与订阅

    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:'男'})
        }
  5. 父子之间传东西props

    <Item xxx={this.xxx}/>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CC_Waiting

我,大学未工作,感谢您的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值