[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 ...
随机推荐
- vue -- config.js 配置跨域文件
1.在使用vue开发的时候经常要涉及到跨域的问题,其实在vue cli中是有我们设置跨域请求的文件的. 2.当跨域无法请求的时候我们可以修改工程下config文件夹下的index.js中的dev -- ...
- CentOS下编译安装Apache
与Apache 2.2.x相比,Apache 2.4.x提供了很多性能方面的提升,包括支持更大流量.更好地支持云计算.利用更少的内存处理更多的并发等.除此之外,还包括性能提升.内存利用.异步 I/O的 ...
- Ubuntu 12.04使用演示
今年年初,发布了Ubuntu 12.04(代号Precise Pangolin),但正式版预计将于2012年的4月底发布,作者对最新版本的ubuntu做了试用,先将操作视频与大家分享.更多内容请关注本 ...
- Regularization —— linear regression
本节主要是练习regularization项的使用原则.因为在机器学习的一些模型中,如果模型的参数太多,而训练样本又太少的话,这样训练出来的模型很容易产生过拟合现象.因此在模型的损失函数中,需要对模型 ...
- css3 transform:scale(x)实现字体的缩放:
css3 transform:scale(x)字体的缩放: transform:scale(x),针对于整体的缩放,缩放的整体包括宽,高,背景.这自然对于内联元素就无法使用此属性,最好使用无属性的sp ...
- HDU 4696 Answers 水题
http://acm.hdu.edu.cn/showproblem.php?pid=4696 由题意可知 1<=Ci<=2 而且图上一定有环 那么我们可以得出: 只要存在奇环(即Ci=1) ...
- cat---查看文件内容
- 【例题 8-13 UVA - 11093】Just Finish it up
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 尺取法. 假设现在取[l..r]这一段. 然后发现累加的和小于0了. 那么方法只能是不走l..l+1这一段了 即delta递减(p[ ...
- 漫话Unity(二)
三.Unity编辑器介绍 Unity是一个商业级的3d游戏引擎.一个引擎的专业程度事实上并非体如今它多么牛b 的次世代效果,说实话那些效果即便你会用也不敢用.由于没有哪个手机是次世代的. 游戏引擎的专 ...
- [AngularFire] Firebase OAuth Login With Custom Firestore User Data
import { NgModule } from '@angular/core'; import { AuthService } from './auth.service'; import { Ang ...