react-redux基本使用

安装:

npm install react-redux --save

异步任务中间件:redux-thunk redux-logger

npm install redux-thunk redux-logger --S

使用

store部分:引入了redux,使用了createStore(创建store),combineReducers(合并reducers),applyMiddleware(使用中间件)三个函数,使用了两个中间件redux-logger(日志打印), redux-thunk(异步处理)
counterReducer部分:传入state和action,返回新的state,传给store
init.js部分:引入react-redux,用Provider标签包裹,传递store实例
reactReduxPage部分:定义了add,minus,asncAdd三个函数
page部分:使用了react-redux的connect的高阶组件

src/pages/ReactReduexPage.js

import React, { Component } from 'react'
import {connect} from 'react-redux';
import {add, minus,asncAdd} from "../action/reactReduxPage"

class ReactReduxPage extends Component {
    render() {
        const {counter,dispatch,add,minus,asncAdd} = this.props;
        return (
            

{counter}

{/* */}
) } } //connect是高阶函数 export default connect( //mapStateToProps state => ({counter: state.counter}), //mapDispatchToProps { add,minus,asncAdd } )(ReactReduxPage);

src/store/counterReducer.js

export function counterReducer(state=0,action){
    switch(action.type){
        case 'add':
            return state + 1;
        case 'minus':
            return state - 1;
        default:
            return state;
    }
}
 

src/store/ReactReduxStore.js

import {createStore, combineReducers,applyMiddleware} from 'redux';
import logger from "redux-logger";
import thunk from "redux-thunk";
import {counterReducer} from './counterReducer';

const store = createStore(
    combineReducers({
        counter: counterReducer
    }),
    applyMiddleware(thunk,logger),
);

export default store;

src/action/reactReduxPage.js

export const add = () => ({type: "add"})
export const minus = () => ({type: "minus"})
export const asncAdd = () => dispatch => {
    setTimeout(() => {
        dispatch({type:"add"});
    },1000);
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import store from './store/ReactReduxStore';
import {Provider} from 'react-redux';
// const render = () => {
    ReactDOM.render(
    
        
    , document.getElementById('root'));
// }


你可能感兴趣的:(react-redux基本使用)