博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[PReact] Integrate Redux with Preact
阅读量:6888 次
发布时间:2019-06-27

本文共 2922 字,大约阅读时间需要 9 分钟。

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. 

 

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(    
, 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 (            
{(loading && !userState) ?

Fetching {user}'s profile

:
}
); }}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);

 

转载地址:http://qmqbl.baihongyu.com/

你可能感兴趣的文章
Robot Framework + Selenium library + IEDriver环境搭建
查看>>
第220天:Angular---路由
查看>>
Android中XML解析-PULL解析
查看>>
mysql小记--基础知识
查看>>
Java验证码
查看>>
vue 编辑
查看>>
【状压DP】【NOIP提高组】愤怒的小鸟
查看>>
MVC, MVP, MVVM总结——MVC篇
查看>>
汤炒栗子
查看>>
四川大学师生莅临现场
查看>>
跨域ajax原理(jsonp方式)
查看>>
Discover a powerful and suitable Javascript Automatic Testing Toolkit
查看>>
软件测试第三次作业
查看>>
bzoj 4372 烁烁的游戏——动态点分治+树状数组
查看>>
检测浏览器版本太低 提示用户下载其他浏览器
查看>>
Evosuite使用方法入门
查看>>
Python urllib模块
查看>>
VC++ CStatic控件背景透明且改变其文本时,文字重叠解决方法
查看>>
WPF学习笔记——ListBox用ItemsSource绑定数据源
查看>>
ASP.NET MVC中的嵌套布局页
查看>>