路由组件之间的参数传递
父子组件之间的内容传递,可以通过 props 来进行参数传递,但是路由组件却没有自己的标签,那么该如何进行参数的传递呢? 用路由组件特有的 props ,我们可以利用 History API 的一些特性来进行路由组件之间的参数传递,有三种方法。
1. 传递 params 参数
class Parent extends Component {
state = {
messageArr:[
{id:"01", title: "消息1"},
{id:"02", title: "消息2"},
{id:"03", title: "消息3"},
]
}
render() {
const {messageArr} = this.state;
return (
<div>
<ul>{
messageArr.map(item=>{
return <li key={item.id}><Link to={`/home/message/detail/${item.id}/${item.title}`}>{item.title}</Link></li>
})
}</ul>
<hr/>
{}
<Route path="/home/message/detail/:id/:title" component={Child} />
</div>
)
}
}
class Child extends Component {
state = {
contentArr:[
{id:"01", content: "你好中国"},
{id:"02", content: "你好世界"},
{id:"03", content: "你好帅哥"},
]
}
render() {
console.log(this.props);
const {id, title} = this.props.match.params
const findResult = this.state.contentArr.find(obj=>obj.id == id).content;
return (
<div>
<ul>
<li>ID: {id}</li>
<li>TITLE: {title}</li>
<li>CONTENT: {findResult}</li>
</ul>
</div>
)
}
}
在使用 params 传递参数时,你会清楚的看到参数以路由的形式展现了出来,例如:
http://localhost:3000/home/message/用户1/文章32
类式上面的用户1和文章32,这就是传递的参数。 以params 方式传递的参数,在路由中需要声明接受才可以使用。
<Route path="/home/message/detail/:id/:title" component={Child} />
后面的 :id 与 :title 就是可变路由,可以通过props 的match 接受接收这里的内容.
const {id, title} = this.props.match.params
2. 传递 search 参数
这个就是依赖 get 的请求方式。
http://localhost/home/message?id=1&title=abc
即 javascript 可以获取到 url 中 ? 后面的请求体。 所以我们可以吧上面的 map 中返回的标签修改以下
<li key={item.id}><Link to={`/home/message/detail?id=${item.id}&title=${item.title}`}>{item.title}</Link></li>
且这种方式不需要在路由中声明接收。 通过 props 中的 location 进行接收
const search = this.props.location.search;
const {id, title} = qs.parse(search.slice(1));
3. 传递 state 参数
通过 HistoryAPI 来进行数据传输:
<li key={item.id}><Link to={{pathname: `/home/message/detail`, state:{id:item.id, title:item.title}}}>{item.title}</Link></li>
不需要在路由链接中添加任何东西,也不需要路由进行声明接收。更加的美观。 在 props 中的 location 里获取 state 属性
const {id, title} = this.props.location.state;
4. 三者对比
路由组件传参其实用的较少,因为他们都有对某些东西的依赖:
params : 依赖于路由链接,链接不美观search : 依赖于路由链接,链接不美观state : 依赖于历史记录 (HistoryAPI ),链接美观,但是当直接输入链接时则会报错(没有历史记录)
所以尽量使用其他的传参方式,如果非要使用的话,有限度比较为:
params (最为常用)search (较为常用)state (比较少用)
样式引入总结
-
import React,{Component} form “react” -
-
在脚手架内,React组件的样式改为 xxx.module.css -
就可以像引入依赖一样引入了 -
import hello from “./index.modul.css” 这里的hello 就是css样式 -
使用 <h2 className = {hello.title}></h2>
知识小结
-
可通过此方法,来定点修改对象中的某一个属性 let obj1 = {a:1,b:2}
let obj2 = {...obj1,b:3}
console.log(obj2); // {a:1,b:3}
-
delete关键字 let obj1 = {a:1,b:2,c:3}
delete obj1.c
console.log(obj1);
// {a:1,b:2}
用来删除对象中的属性.
|