博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Preact] Integrate react-router with Preact
阅读量:5282 次
发布时间:2019-06-14

本文共 2153 字,大约阅读时间需要 7 分钟。

React-router is the community favourite routing solution - it can handle all of your complex routing needs and in this lesson we’ll cover what’s needed to enable it’s use within Preact. 

 

in webpack.config.js:

resolve: {        alias: {            'react': 'preact-compat',            'react-deom': 'preact-compat'        }    },

Add resolve block. it alias 'react' to use 'preact-compat'.

 

Change Route definations.

import {h} from 'preact';import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';import Profile from './Profile';import Home from './Home';import Error from './Error';export default function App() {    return (        
);}

Using 'Switch' to allow only one component showing at a time.

 

Dealing with navigation:

import { h } from 'preact';import {withRouter} from 'react-router-dom';function search(router, query) {    router.history.push(`/profile/${encodeURIComponent(query)}`);}const Home = withRouter((router) => {    return (        

Enter a Github Username

search(router, e.target.value)} />
);});export default Home;

We can use High Order component 'withRouter', it inject 'router' param into our component, then we can use:

router.history.push(`/profile/${encodeURIComponent(query)}`);

to nav around.

 

Get router params:

componentDidMount() {        const username = this.props.match.params.user;        fetch(`${config.url}/${username}`)            .then(resp => resp.json())            .then(user => {                this.setState({                                  user,                                  loading: false                              });            })            .catch(err => console.error(err));    }

You can get the router param by using:

const username = this.props.match.params.user;

 

Link tag:

import {h} from 'preact';import {Link} from 'react-router-dom';export default Error = () => (    

Error!

Home
);

 

转载于:https://www.cnblogs.com/Answer1215/p/7054400.html

你可能感兴趣的文章
hdu 1028 Ignatius and the Princess III(母函数入门+模板)
查看>>
Ubuntu下配置安装telnet server
查看>>
Codeforces 235 E Number Challenge
查看>>
ubuntu 常见命令整理
查看>>
EJBCA安装教程+postgresql+wildfly10
查看>>
(五十四)涂鸦的实现和截图的保存
查看>>
配置EditPlus使其可以编译运行java程序
查看>>
java中的占位符\t\n\r\f
查看>>
7.14
查看>>
SDN2017 第一次作业
查看>>
MySQL通过frm 和 ibd 恢复数据过程
查看>>
SRS源码——Listener
查看>>
Java面向对象抽象类案例分析
查看>>
对SPI、IIC、IIS、UART、CAN、SDIO、GPIO的解释
查看>>
Thymeleaf模板格式化LocalDatetime时间格式
查看>>
庖丁解“学生信息管理系统”
查看>>
Pyltp使用
查看>>
其他ip无法访问Yii的gii,配置ip就可以
查看>>
使用json格式输出
查看>>
php做的一个简易爬虫
查看>>