kotlin-react-router-dom
kotlin-react-router-dom 是JetBrains官方为支持ReactRouter提供的包。实现单页面路由功能。
引入包
在build.gradle文件中添加如下代码:
implementation("org.jetbrains:kotlin-react-router-dom:5.1.2-pre.113-kotlin-1.4.0")
使用
在kotlin中使用ReactRouter与React中没有什么不同,先看官方提供的代码示例:
interface IdProps : RProps {
var id: Int
}
class RootComponent : RComponent<RProps, RState>() {
override fun RBuilder.render() {
hashRouter { // or "browserRouter"
switch {
route("/", IndexComponent::class, exact = true)
route("/login", strict = true) {
login(providers = listOf("plain", "facebook"))
a(href = "#/") {
+"Back"
}
}
route<IdProps>("/user/:id") { props ->
div {
+"User id: ${props.match.params.id}"
}
}
redirect(from = "/redirect", to = "/redirected")
}
}
}
}
最外层包裹一个hashRouter 或者browserRouter 组件,关于它们的区别稍后再说。hashRouter 内部添加了switch组件,route组件是用来路由到具体的路径,如果需要获取路径中的参数,可以用:id 做占位符,然后通过props.match.params.id进行访问, redirect是重定向该路径。总体使用形式有点像Switch语法。
开始一个Demo
- 新建一个App.kt文件,创建一个App组件,并在入口处注册。
fun main() {
window.onload = {
render(document.getElementById("root")) {
child(App::class) {}
}
}
}
class App(props: RProps) : RComponent<RProps, RState>(props) {
override fun RBuilder.render() {
div {
a(href = "#/"){+"Home"}
}
div {
a(href = "#/p2"){+"PAGE2"}
}
div {
a(href = "#/p3"){+"PAGE3"}
}
hashRouter {
switch {
route("/",exact = true){
div {
+"Home页面"
}
}
route("/p2"){
div {
+"p2页面"
}
}
route("/p3"){
div {
+"p3页面"
}
}
}
}
}
}
- 运行效果
由上面代码应该注意到它的url为什么和常见的url不一样,为什么会多一个**#** 符号,这是因为hashRouter使用的是URL的hash部分,以保证url和UI的一致性。并且它不支持location.key 和location.state。如果我们切换成**browserRouter ** 呢?
出现了Connot GET /p2的错误。这是因为browserRouter 的路由方式和浏览器一样,他会直接调用浏览器请求/p2链接,而由于我们这是单页面应用,服务器资源只存在一个index.html页面,自然就无法请求到相应的数据,那我们该如何解决这个问题呢。只需要在Nginx服务器配置中加上:
location / {
··· ···
try_files $uri /index.html;
··· ···
}