React(脚手架)——create-react-app撸api
2019-03-11 本文已影响0人
感觉不错哦
传值其实本质还是只有一个,就是获取query!获取query的方式不一样,最常见的就是获取url参数数据,当然也有通过缓存比如说localstorage或者cookie
动态路由

新建一个组件,并且已经配置好了 路由

现在我们编辑之前一个写过的路由,并且让他跳转

注意我在这个组件中使用了Link,那么我们就要在上方引入这个Link,这步很重要

此时点击按钮自然而然的就跳转到了content组件页面,OK此时我们想获取点击的同时获取aid
有vue或者是node基础的小伙伴应该晓得了动态路由怎么配,就是:xxx

在/content后方加上:参数即可,当然这是路由的配置,传参的配置还没好,既然是变量,那我们在传参的时候to里面应该就是{}表达式

此时再点击链接的时候,url上就出现了对应的aid

那当然这样写不推荐,推荐ES6的模板字符串

OK~~~
如何获取参数呢,我们可以在Content的生命周期函数中打印一下


当然这个参数不是传参决定的是路由配置的时候决定的

如果这里改变了一下那么key就变成bid了
get传值
get传值用的也比较广泛完全看自己个人喜好,get传值其实就是获取url中的数据,就像平时URL的location.search

把配置搞回原样,然后在Link中添加参数

那么这时候数据就会在URL中显示出来

此时处理的方法就有很多了,你可以直接使用原生JS的window.location.search方法处理,也可以使用react

此时控制台就会打印 ?aid=2
如何处理这个,方法很多,比如写个原生的写法


如果说参数多的话,这种方法就会很麻烦。那熟悉node的小伙伴肯定知道url是可以解析这种域名的

通过es5的方法引入url,然后使用url.parse

成功获取到参数,而且继续加参数也无所畏惧,当然你用react也是一样的

如果你不想让别人知道你传了啥,开启你的猥琐模式的话,可以使用下面这个方法


