在入口文件
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)(组件)