[PReact] Handle Simple Routing with preact-router

Some applications only need a very minimal routing solution. This lesson will cover a practical example showing the router in use. We’ll build a simple search feature that accepts user input and then calls the github API. We’ll see how to access route parameters, how to manually & automatically navigate around, and finally how to handle un-matched path. https://github.com/developit/preact-router

Install:

npm install --save preact-router

Define routers:

import {h} from ‘preact‘;
import { Router } from ‘preact-router‘;
import Profile from ‘./Profile‘;
import Home from ‘./Home‘;
import Error from ‘./Error‘;

export default function App() {
    return (
        <Router>
            <Home path="/" />
            <Profile path="/profile/:user"/>
            <Error default/>
        </Router>
    );
}

Defailt Error router:

import {h} from ‘preact‘;
import {route} from ‘preact-router‘;

const back = (e) => {
    route(‘/‘);
};

export default Error = () => (
    <div>
        <h2>Error!</h2>
        <button onClick={e => back(e)}>Home</button>
    </div>
);

Home: preact call route() function to navigate between components.

import { h } from ‘preact‘;
import { route } from ‘preact-router‘;

function search(query) {
    route(`/profile/${encodeURIComponent(query)}`);
}

export default function Home() {
    return (
        <section>
            <p>Enter a Github Username</p>
            <input type="search"
                   placeholder="username"
                   onSearch={e => search(e.target.value)}
            />
        </section>
    );
}

Profile.js: Stateful component, fetching data:

import {h, Component} from ‘preact‘;
import User from ‘./User‘;

const config = {
    url: ‘https://api.github.com/users‘
};

export default class Profile extends Component {
    constructor(props) {
        super(props);

        this.state = {
            loading: true,
            user: null
        };
    }

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

    render({user: username}, {loading, user: userState}) {
        return (
            <div class="app">
                {loading
                    ? <p>Fetching {username}‘s profile</p>
                    : <User image={userState.avatar_url}
                            name={userState.name} />
                }
            </div>
        );
    }
}
时间: 2024-08-06 01:48:50

[PReact] Handle Simple Routing with preact-router的相关文章

Preact:Into the void 0(译)

本文整理自Jason Miller在JSConf上的talk.原视频地址: https://www.youtube.com/watch?v=LY6y3HbDVmg 开场白 嗨,大家好,我是Jason,Github上那个developit和推特上的_developit,是一系列库的作者(serial library author),我喜欢甜甜圈.肉汁乳酪薯条和斧头,这意味着我是加拿大人(枫叶国的人喜欢斧头--在加拿大把扔斧头做成15万用户的大生意). 我也喜欢"限制".我在移动web广泛

Routing Manager for WCF4 z

http://www.codeproject.com/Articles/77198/Routing-Manager-for-WCF Download source Contents Features Introduction Concept and Design Usage and Test Implementation Conclusion Features Manageable Routing Service Mapping physical to logical endpoints Man

PCI Express(六) - Simple transactions

原文地址:http://www.fpga4fun.com/PCI-Express6.html Let's try to control LEDs from the PCI Express bus. Xilinx's "Endpoint Block Plus" core allows us to work at the transaction layer level, so it's just going to take us a few lines of code.Instead of

TCP/IP illustrated 第九、十章 IP Routing &amp; Dynamic Routing Protocols

IP routing Summary 定义: IP routing 指的是 IP 如何 make routing decisions,即将 IP datagram 发到哪里去.基础:IP routing 的基础是 IP routing table, 每次发送 IP datagram 的时候,都会参照 routing table,选择合适的 route, 然后发送.IP routing table 可以创建和修改,其方法如下: 通过 ICMP redirect message 改动 通过 user

Express 4.x API

express() express()用来创建一个Express的程序.express()方法是express模块导出的顶层方法. var express = require('express'); var app = express(); Methods express.static(root, [options]) express.static是Express中唯一的内建中间件.它以server-static模块为基础开发,负责托管 Express 应用内的静态资源. 参数root为静态资源

Information Centric Networking Based Service Centric Networking

A method implemented by a network device residing in a service domain, wherein the network device comprises an information centric networking (ICN) transport layer and a service access layer (SAL) for handling context-aware service logistics and serv

真实场景中WebRTC 用到的服务 STUN, TURN 和 signaling

FQ收录转自:WebRTC in the real world: STUN, TURN and signaling WebRTC enables peer to peer communication. BUT... WebRTC still needs servers: For clients to exchange metadata to coordinate communication: this is called signaling. To cope with network addre

Express中文文档

Express 4.x API express 翻译 api文档 中文 -- express() express()用来创建一个Express的程序.express()方法是express模块导出的顶层方法. var express = require('express'); var app = express(); Methods express.static(root, [options]) express.static是Express中唯一的内建中间件.它以server-static模块为

The main concepts

The MVC application model A Play application follows the MVC architectural pattern applied to the web architecture. This pattern splits the application into separate layers: the Presentation layer and the Model layer. The Presentation layer is furthe