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:

  1. yarn add redux redux-thunk preact-redux

Set up:

  1. import {h, render} from 'preact';
  2. import {Provider} from 'preact-redux';
  3. import thunk from 'redux-thunk';
  4. import {createStore, applyMiddleware, compose} from 'redux';
  5. import App from './components/App';
  6. import reducer from './reducer';
  7.  
  8. const initialState = {
  9. loading: true,
  10. user: null
  11. };
  12.  
  13. const composeEnhancers =
  14. typeof window === 'object' &&
  15. window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
  16. window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
  17. // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
  18. }) : compose;
  19.  
  20. const store = createStore(reducer, initialState, composeEnhancers(applyMiddleware(thunk)));
  21.  
  22. render(
  23. <div>
  24. <Provider store={store}>
  25. <App />
  26. </Provider>
  27. </div>,
  28. document.querySelector('main'));

Reducer:

  1. export default function (state, action) {
  2. switch (action.type) {
  3. case 'FETCH_USER':
  4. return {
  5. user: null,
  6. loading: true
  7. };
  8. case 'USER_FETCHED':
  9. return {
  10. user: action.payload,
  11. loading: false
  12. };
  13.  
  14. default:
  15. return state;
  16. }
  17. }

Action creator:

  1. const config = {
  2. url: 'https://api.github.com/users'
  3. };
  4.  
  5. export function fetchUser(username) {
  6. return function (dispatch) {
  7. dispatch({type: 'FETCH_USER'});
  8. fetch(`${config.url}/${username}`)
  9. .then(resp => resp.json())
  10. .then(user => {
  11. dispatch({type: 'USER_FETCHED', payload: user})
  12. })
  13. .catch(err => console.error(err));
  14. }
  15. }

Component:

  1. import {h, Component} from 'preact';
  2. import User from './User';
  3. import {fetchUser} from '../actions';
  4. import {connect} from 'preact-redux';
  5.  
  6. export class Profile extends Component {
  7.  
  8. componentDidMount() {
  9. const username = this.props.match.params.user;
  10. this.props.fetchUser(username);
  11. }
  12.  
  13. render({loading, userState, user}) {
  14. return (
  15. <div class="app">
  16. {(loading && !userState)
  17. ? <p>Fetching {user}'s profile</p>
  18. : <User name={userState.name} image={userState.avatar_url}></User>
  19. }
  20. </div>
  21. );
  22. }
  23. }
  24.  
  25. const mapStateToProps = (state) => {
  26. return {
  27. userState: state.user,
  28. loading: state.loading
  29. };
  30. };
  31. const mapDispatchToProps = (dispatch) => {
  32. return {
  33. fetchUser: (username) => dispatch(fetchUser(username))
  34. };
  35. };
  36.  
  37. export default connect(
  38. mapStateToProps,
  39. mapDispatchToProps
  40. )(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. ElasticSearch 在Hadoop生态圈的位置

    它的位置非常清晰,直接贴图. 更详细点,见

  2. Maven学习详解(13)——Maven常用命令大全与pom文件讲解

    一.Maven常用命令 1.1.Maven 参数 -D 传入属性参数  -P 使用pom中指定的配置  -e 显示maven运行出错的信息  -o 离线执行命令,即不去远程仓库更新包  -X 显示ma ...

  3. iOS 基于第三方QQ授权登录

    基于iOS实现APP的第三方QQ登陆.接入第三方SDK时的一个主要的步骤: 1,找到相关的开放平台.QQ互联平台,http://connect.qq.com/: 2,注冊成功后创建自己的APP.填写一 ...

  4. windows 2016 配置 VNC 服务

    windows 2016 配置 VNC 服务 下载windows版 https://www.realvnc.com/download/vnc/ 安装时勾选 vncserver 进入 "C:\ ...

  5. 教你win7解除阻止程序运行怎么操作

    教你win7解除阻止程序运行怎么操作 来源:http://www.windows7en.com/jiaocheng/27594.html 有时候我下载的软件,被win7系统禁止了运行了时软件不能使用, ...

  6. Android学习笔记进阶十二之裁截图片

    package xiaosi.cut; import java.io.File; import android.app.Activity; import android.content.Intent; ...

  7. Ajax : $. get()和$.post() $.getScript $.getJSON

    <body> <input type="button" value="Ajax" /> <div id="box&quo ...

  8. LoadRunner IP欺骗使用

  9. iOS 友盟分享

    iOS 友盟分享 这个主要是提到怎样通过友盟去自己定义分享的步骤: 一.肯定要去友盟官网下载最新的SDK包,然后将SDK导入到你的project目录里面去. 二.注冊友盟账号.将你的APP加入到你的账 ...

  10. 用c实现的各种排序的方法

    #include <stdio.h> void swap(int *a, int *b); void bubble_sort(int a[], int n); void select_so ...