react(任意组件之间传值--消息订阅与发布、路由)

目录

 兄弟组件传值--任意组件之间传值

fetch发送请求:

react 路由

解决样式丢失的问题:

路由的模糊匹配和严格匹配

嵌套路由

向路由组件传参


前端中文学习网站:印记中文 - 深入挖掘国外前端新领域,为国内 Web 前端开发人员提供优质文档!

1. 搜索github 用户的案例: 地址: https://api.github.com/search/users?q=xx

 兄弟组件传值--任意组件之间传值

消息的订阅与发布

1. 装包: yarn add 'pubsub-js'   

注意包名不允许有大写

引入:

import PubSub from 'pubsub-js'

// or when using CommonJS
const PubSub = require('pubsub-js');

例子:

// create a function to subscribe to topics
var mySubscriber = function (msg, data) {
    console.log( msg, data );
};

// add the function to the list of subscribers for a particular topic
// we're keeping the returned token, in order to be able to unsubscribe
// from the topic later on
var token = PubSub.subscribe('MY TOPIC', mySubscriber);

// publish a topic asynchronously
PubSub.publish('MY TOPIC', 'hello world!');

// publish a topic synchronously, which is faster in some environments,
// but will get confusing when one topic triggers new topics in the
// same execution chain
// USE WITH CAUTION, HERE BE DRAGONS!!!
PubSub.publishSync('MY TOPIC', 'hello world!');

取消订阅:

// add the function to the list of subscribers to a particular topic
// we're keeping the returned token, in order to be able to unsubscribe
// from the topic later on
var token = PubSub.subscribe('MY TOPIC', mySubscriber);

// unsubscribe this subscriber from this topic
PubSub.unsubscribe(token);

fetch发送请求:

关注分离的设计思想

不需要用xhr 发送请求--内置对象

.then() 的链式调用

终端promise链:

.them(

()=>{}

(errro)=>{

return new Promise(()=>{})

})

优化: 把有可能出错的代码写在try中,用catch捕获

 

react 路由

前端路由的工作原理: 依靠浏览器的 history

<Link to='/xxx'>able</Link>

<Route path='/xxx' component={Dome} />

<BrowserRouter></BrowserRouter>

<HashRouter></HashRouter>

<Switch>包裹多个route</Switch>

<Redirect to=' ' />

一般组件、路由组件  路由组件会受到一些porps: history,location,match

标签体内容是一个特殊的标签属性,储存在this.props.children 中

解决样式丢失的问题:

1. 使用HashRouter 因为#后面的值默认是前端的,发请求的时候不带给服务器

2. 将相对路径改为绝对路径

路由的模糊匹配和严格匹配

在route中开启精准匹配: exact={true}

嵌套路由

1. 注册子路由需要写上父路由的path 值

2. 路由的匹配是根据注册路由的顺序

向路由组件传参

1. 使用 this.props.match.params

获取:   ‘ :id/:title ’

 2. 传递 sreach 参数

取: this.props.location.search

需要借助 ‘querystring’ 这个内置库进行解析

通过? 和 &传递: (urlencoded 编码)

 【拓】ajax 传递参数的形式:

 3. state 传递,可以不用显示在url地址中

 取: this.props.location.state

 刷新不丢

路由跳转的两种模式:

push 、 repalce

默认是压栈的push操作,开启repalce :

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值