[PReact] Integrate Redux with Preact
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的更多相关文章
- [Preact] Integrate react-router with Preact
React-router is the community favourite routing solution - it can handle all of your complex routing ...
- [AngularJS NG-redux] Integrate Redux Devtools
In this lesson, we are going to learn how to integrate Redux Devtools into our Angular application. ...
- Preact(React)核心原理详解
原创: 宝丁 玄说前端 本文作者:字节跳动 - 宝丁 一.Preact 是什么 二.Preact 和 React 的区别有哪些? 三.Preact 是怎么工作的 四.结合实际组件了解整体渲染流程 五. ...
- Taro 3.4 beta 发布: 支持 Preact 为应用开辟更多体积空间
项目体积是困扰小程序开发者的一大问题,如果开发者使用 Taro React 进行开发,更是不得不引入接近 100K 的 React 相关依赖,这让项目体积变得更加捉襟见肘.因此,Taro v3.4 的 ...
- Using Immutable in React + React-Redux
React-Redux Introduction React-Redux is a library for React based on Redux package. And the core ide ...
- React与Preact差异之 -- setState
Preact是React的轻量级实现,是React比较好的替代者之一,有着体积小的优点,当然与React之间一定会存在实现上的差异,本文介绍了在 setState 方面的差异之处. 源码分析 首先来分 ...
- [PReact] Handle Simple Routing with preact-router
Some applications only need a very minimal routing solution. This lesson will cover a practical exam ...
- [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 ...
- [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 ...
随机推荐
- spark读写mysql
spark读写mysql除官网例子外还要指定驱动名称 travels.write .mode(SaveMode.Overwrite) .format("jdbc") .option ...
- Shiro + SSM(框架) + Freemarker(jsp)
Shiro + SSM(框架) + Freemarker(jsp)讲解的权限控制Demo,还不赶快去下载? 我们知道Ajax不能做页面redirect和forward跳转,所以Ajax请求假如没登录, ...
- POJ 1269 Intersecting Lines 直线交
不知道谁转的计算几何题集里面有这个题...标题还写的是基本线段求交... 结果题都没看就直接敲了个线段交...各种姿势WA一遍以后发现题意根本不是线段交而是直线交...白改了那个模板... 乱发文的同 ...
- 12、UVC&V4L2的关系
UVC是一种usb视频设备驱动.用来支持usb视频设备,凡是usb接口的摄像头都能够支持 V4L2是Linux下的视频采集框架.用来统一接口,向应用层提供API UVC: USB video clas ...
- 洛谷 P1801 黑匣子_NOI导刊2010提高(06)(未完)
P1801 黑匣子_NOI导刊2010提高(06) 题目描述 Black Box是一种原始的数据库.它可以储存一个整数数组,还有一个特别的变量i.最开始的时候Black Box是空的.而i等于0.这个 ...
- Excel VBA简单使用——数据缺失处理
VBA(Visual Basic for Applications)是VB的一种宏语言.用来扩展应用程式的功能.特别是Microsoft Office软件. 转载请注明原文地址:http://blog ...
- 使用框架的php假设使用定时服务Cronjob
工作须要用php开发了个监控的小程序,既然是监控就须要定时运行. 之前我用的是chrome加个定时刷新的小插件,放在server上执行.也能实现,就是别扭. 通用正规的做法应该是:linux上的Cro ...
- 内存泄漏与指针悬挂&野指针介绍
内存泄漏概念:内存泄漏时指动态申请的内存空间没有正常释放,但是也不能继续使用的情况. 例如: char *ch1; ch1 = new char('A'); char = *ch2 = new cha ...
- 28.semaphore跨进程通信
根据id创建Semaphore,并初始化有一个信号量可用 name类型是char *...; HANDLE hsem = CreateSemaphoreA(NULL, 1, , name); 关闭句柄 ...
- Bitmap Image Graphics
Bitmap Image Graphics private void DrawImagePointF(PaintEventArgs e){ // Create image. Image new ...