redux

在入口文件

import React from "react";
import ReactDom from "react-dom";
import App from "./App";
import store from "./store";
import { Provider } from "react-redux";
import { BrowserRouter as Router } from "react-router-dom";
ReactDom.render(
    <Provider store={store}>
        <Router>
            <App />
        </Router>
    </Provider>,
    document.querySelector("#root")
);

在src创建store/index.js


import rootReducer from '../reducer/index'

import thunk from 'redux-thunk'      //yarn add redux-thunk/ redux-saga

const store = createStore(rootReducer, applyMiddleware(thunk))

export default store

创建reducer/index.js

import { combineReducers } from "redux";
import  homeReducer from ''./homeReducer''
const rootReducer = combineReducers({
  ...Reducer
});
export default rootReducer;


创建reducer/homeReducer

import { HOME_TREES, HOME_TREES_DETAIL, HOME_TREES_PAY, HOME_TREES_ORDER_FORM } from '../action/actionType'
//导入动作类型
const initState = {//定义初始状态
   state:''
}
const homeReducer = (state = initState, action) => {
    const newState = { ...state }//浅拷贝
    switch (action.type) {//赋值
        case ACTIONTYPE:
            newState.state = action.payload
            break;     
        default:
            break;
    }
    return newState
}
export default homeReducer  

创建action/actionType.js

export const ACTIONTYPE='ACTIONTYPE'

创建action/index.js

import { ACTIONTYPE } from "./actionType";
import request from ‘./request.js’//引入封装的axios
export const fun= (args) => {
    return async dispatch => {//发送请求
        const result = await request({
            url: '/dream/friends',
            params: {args }
        })
   
        const action = {
            type:ACTIONTYPE ,
            payload: result.data.data
        }  
        dispatch(action)  //发送到reducer
    }

}

在组件中

import { fun } from '../../action/index.js'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'

定义组件

//connect 接收两个参数mapStateToProps、mapDispatchToProps

const mapStateToProps = (state) => {
    return {
        state: { ...state }       //所有reducer
        //state :state.homeReducer  指定的reducer
    }
}
const mapDispatchToProps = dispatch => bindActionCreators({ 
从action/index.js导出的方法
//fun,....
 }, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(组件)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值