在react中使用redux+redex-thunk

需要安装的依赖

redux
redux-thunk 默认的redux不支持异步,需要引入中间件
react-redux 结合react使用时需要引入

创建store

import {
    createStore,
    applyMiddleware,
    compose
} from 'redux';

// redux-thunk中间件可以使redux支持异步action
import thunk from 'redux-thunk';

import rootReducer from './reducer';

// 默认只支持同步方式
const store = createStore(rootReducer);
// 使用 __REDUX_DEVTOOLS_EXTENSION__ 是为了启用redux—devtools扩展程序,方便开发调试
const store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

// 使用中间件支持异步方式
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(applyMiddleware(...[thunk]));
const store = createStore(rootReducer, enhancer);

创建reducer

// reducer是纯函数,接收state和action两个参数
const reducer = (state = {}, action) => {
    switch (action.type) {
        case 'UPDATE_NAME':
            return {
                ...state,
                name: action.name
            }
    }

    return {
        ...state
    }
}

// 如果要将reducer拆分,需要从redux中引入combineReducers来合并不同的reducer
import { combineReducers } from 'redux';

const rootReducer = combineReducers({
    reducer1,
    reducer2,
})

创建action

// action是一个对象,包含type字段,使用 store.dispatch 触发
store.dispatch({
    type: 'UPDATE_NAME',
    name: '张三',
})

结合react

根组件中的处理
// 从react-redux中引入Provider
import { Provider } from 'react-redux';

// 将Provider包裹在根组件外面,并传入store
ReactDOM.render((
    <Provider store={store}>
        <div>
            <User />
            <News />
        </div>
    </Provider>
), document.getElementById('root'));
子组件中的处理
// 在子组件中从react-redux引入connect
import { connect } from 'react-redux';

// 在到处子组件的时候,使用connect方法包裹组件
export default connect(mapStateToProps, mapDispatchToProps)(Component);

// connect接收四个参数,分别是mapStateToProps,mapDispatchToProps,mergeProps,options
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

// mapStateToProps(state, ownProps)方法允许我们将store中的数据作为props绑定到组件中
// 只要store更新了就会调用mapStateToProps方法,mapStateToProps返回的结果必须是object对象,该对象中的值将会更新到组件中
const mapStateToProps = state => {
    return {
        newsList: state.newsReducer.newsList,
    }
}

// mapDispatchToProps(dispatch,[ownProps])方法可以将action作为props绑定到组件中
// mapDispatchToProps可以是方法也可以是对象

const mapDispatchToProps = (dispatch) => {
    return {
        fetchPosts: () => {
            fetch('https://jsonplaceholder.typicode.com/posts')
                .then(function (response, v) {
                    return response.json();
                })
                .then(function (myJson) {
                    dispatch({
                        type: 'UPDATE_LIST',
                        newsList: myJson
                    })
                });
        },
        changeUserName: () => {
            dispatch({
                type: 'UPDATE_NAME',
                name: '张三',
            })
        },
    }
}

// 作为方法使用
export default connect(mapStateToProps, mapDispatchToProps)(News);

const fetchPosts = () => dispatch => {
    fetch('https://jsonplaceholder.typicode.com/posts')
        .then(function (response, v) {
            return response.json();
        })
        .then(function (myJson) {
            dispatch({
                type: 'UPDATE_LIST',
                newsList: myJson
            })
        });
}

const changeUserName = () => dispatch => {
    dispatch({
        type: 'UPDATE_NAME',
        name: '张三',
    })
}

// 作为对象使用
export default connect(mapStateToProps, { fetchPosts, changeUserName })(News);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值