Redux is one of the most popular state-management libraries and although not specific to React, it is widely used with it. This is why the author of Preact has released a package called preact-redux, which is a simple wrapper around the main react-redux package that enables it to be used in a Preact application without any other changes to your codebase. In this lesson we refactor a stateful component to use Redux + Redux-thunk. https://github.com/developit/preact-redux

Install:

yarn add redux redux-thunk preact-redux

Set up:

import {h, render} from 'preact';
import {Provider} from 'preact-redux';
import thunk from 'redux-thunk';
import {createStore, applyMiddleware, compose} from 'redux';
import App from './components/App';
import reducer from './reducer'; const initialState = {
loading: true,
user: null
}; const composeEnhancers =
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
}) : compose; const store = createStore(reducer, initialState, composeEnhancers(applyMiddleware(thunk))); render(
<div>
<Provider store={store}>
<App />
</Provider>
</div>,
document.querySelector('main'));

Reducer:

export default function (state, action) {
switch (action.type) {
case 'FETCH_USER':
return {
user: null,
loading: true
};
case 'USER_FETCHED':
return {
user: action.payload,
loading: false
}; default:
return state;
}
}

Action creator:

const config = {
url: 'https://api.github.com/users'
}; export function fetchUser(username) {
return function (dispatch) {
dispatch({type: 'FETCH_USER'});
fetch(`${config.url}/${username}`)
.then(resp => resp.json())
.then(user => {
dispatch({type: 'USER_FETCHED', payload: user})
})
.catch(err => console.error(err));
}
}

Component:

import {h, Component} from 'preact';
import User from './User';
import {fetchUser} from '../actions';
import {connect} from 'preact-redux'; export class Profile extends Component { componentDidMount() {
const username = this.props.match.params.user;
this.props.fetchUser(username);
} render({loading, userState, user}) {
return (
<div class="app">
{(loading && !userState)
? <p>Fetching {user}'s profile</p>
: <User name={userState.name} image={userState.avatar_url}></User>
}
</div>
);
}
} const mapStateToProps = (state) => {
return {
userState: state.user,
loading: state.loading
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchUser: (username) => dispatch(fetchUser(username))
};
}; export default connect(
mapStateToProps,
mapDispatchToProps
)(Profile);

[PReact] Integrate Redux with Preact的更多相关文章

  1. [Preact] Integrate react-router with Preact

    React-router is the community favourite routing solution - it can handle all of your complex routing ...

  2. [AngularJS NG-redux] Integrate Redux Devtools

    In this lesson, we are going to learn how to integrate Redux Devtools into our Angular application. ...

  3. Preact(React)核心原理详解

    原创: 宝丁 玄说前端 本文作者:字节跳动 - 宝丁 一.Preact 是什么 二.Preact 和 React 的区别有哪些? 三.Preact 是怎么工作的 四.结合实际组件了解整体渲染流程 五. ...

  4. Taro 3.4 beta 发布: 支持 Preact 为应用开辟更多体积空间

    项目体积是困扰小程序开发者的一大问题,如果开发者使用 Taro React 进行开发,更是不得不引入接近 100K 的 React 相关依赖,这让项目体积变得更加捉襟见肘.因此,Taro v3.4 的 ...

  5. Using Immutable in React + React-Redux

    React-Redux Introduction React-Redux is a library for React based on Redux package. And the core ide ...

  6. React与Preact差异之 -- setState

    Preact是React的轻量级实现,是React比较好的替代者之一,有着体积小的优点,当然与React之间一定会存在实现上的差异,本文介绍了在 setState 方面的差异之处. 源码分析 首先来分 ...

  7. [PReact] Handle Simple Routing with preact-router

    Some applications only need a very minimal routing solution. This lesson will cover a practical exam ...

  8. [PReact] Reduce the Size of a React App in Two Lines with preact-compat

    Not every app is greenfield, and it would be a shame if existing React apps could not benefit from t ...

  9. [PReact] Use Link State to Automatically Handle State Changes

    Storing and updating values inside a component’s local state (known as controlled components) is suc ...

随机推荐

  1. POJ 2039 Floyd

    句意理解题 解释输入好啦: 第一行n个数 m场电影 随后m行 每行的第一个数 代表 有k奶牛在这个电影中出现过 随后k个数 是奶牛的编号 如果两头奶牛在同一个电影中出现过 相互度为1 奶牛们的相互度可 ...

  2. exit---退出目前的shell

    exit命令   exit命令同于退出shell,并返回给定值.在shell脚本中可以终止当前脚本执行.执行exit可使shell以指定的状态值退出.若不设置状态值参数,则shell以预设值退出.状态 ...

  3. springboot整合Beetl、BeetlSql实现ajax分页

    Beetl是Bee Template Language的缩写,它绝不是简单的另外一种模板引擎,而是新一代的模板引擎,它功能强大,性能良好,超过当前流行的模板引擎.而且还易学易用. BeetSql是一个 ...

  4. 使用Ant 和 Maven打包发布命令行程序(转载)

    From:https://www.linux178.com/Java/maven-release.html 用Java写了一个命令行的小程序,使用的Intellij IDE是IDEA13原来一直使用A ...

  5. 项目EasyUi和JS中遇到的问题总汇

    近期因为项目用到EasyUi,曾经仅仅是听过,可是没有详细用过.仅仅能一边学一边做.如今将做的过程中遇到的一些难点总结例如以下,以备后用: EsayUi使用: Json格式:key:value,key ...

  6. js18--继承方式

    方式1:子类.prototype = 父类对象 Boy.prototype = new Person(); Sub.prototype = new Sup('张三');   //可以传参数也可以不传 ...

  7. worktools-git 工具的使用总结(知识点累积)

    1.用简单列表的方式查看提交记录git log --pretty=online zhangshuli@zhangshuli-MS-:~/myGit$ git log --pretty=oneline ...

  8. 矩阵乘法java代码实现

    矩阵只有当左边矩阵的列数等于右边矩阵的行数时,它们才可以相乘, 乘积矩阵的行数等于左边矩阵的行数,乘积矩阵的列数等于右边矩阵的列数 即A矩阵m*n,B矩阵n*p,C矩阵m*p: package exa ...

  9. GPU-Z:显卡体质、显卡各传感器实时状态的查看

    1. TechPowerUp GPU-Z:查看显卡体质 下载地址:Download TechPowerUp GPU-Z | techPowerUp 点击 bus interface 后的?进行显卡的体 ...

  10. 求第k大的数(用到快速排序算法的思想)

    //下面两种part效率比较:相同运算量下part比part2快5倍左右,part2写法简单但是效率低 #include "stdafx.h" #include <iostr ...