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. Redis安装以及配置

    下载 http://redis.io/download 解压 tar zxvf redis-2.8.17.tar.gz 编译并安装 1 2 3 4 cd redis-2.8.17 make cd sr ...

  2. CHROME开发者工具的小技巧

    我猜不能转载,但是必须分享. http://coolshell.cn/articles/17634.html

  3. ElasticSearch 工作原理

    ElasticSearch 工作原理图 文字说明,以后更新

  4. js对象基础写法练习

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. java(内部类)

    内部类: 一个类定义在另外一个类的内部就称作为内部类. 内部类的类别: 1.成员内部类: 2.局部内部类: 1.成员内部类: 成员内部类的访问方式: 方式一:在成员内部类的外侧提供一个方法创建内部类的 ...

  6. HDU 1533 Going Home(KM完美匹配)

    HDU 1533 Going Home 题目链接 题意:就是一个H要相应一个m,使得总曼哈顿距离最小 思路:KM完美匹配,因为是要最小.所以边权建负数来处理就可以 代码: #include <c ...

  7. js32---CommonUtil.js

    // BH 命名空间 namespace var BH = {} ; BH.Interface = function(name,methods){ //Interface是类.方法的名字,以后用BH. ...

  8. Java – Reading a Large File Efficiently--转

    原文地址:http://www.baeldung.com/java-read-lines-large-file 1. Overview This tutorial will show how to r ...

  9. 获取input file 选中的图片,并在一个div的img里面赋值src实现预览

    代码如下利用html5实现:几乎兼容所有主流浏览器,当然IE必须是IE 6以上 [jquery代码] $(function() { $("#file_upload").change ...

  10. C++中引用传递与指针传递区别

    C++中引用传递与指针传递区别 在C++中,指针和引用经常用于函数的参数传递,然而,指针传递参数和引用传递参数是有本质上的不同的: 指针传递参数本质上是值传递的方式,它所传递的是一个地址值.值传递过程 ...