import { INCREMENT, DECREMENT } from './constant'
//同步action,值为一般对象
export const createIncrementAction = data => ({ type: INCREMENT, data })
export const createDecrementAction = data => ({ type: DECREMENT, data })
//异步action,值为函数。异步任务有结果后,分发一个同步action操作数据。不是必须要用的,可放在组件中。
export const createIncrementAsyncAction = (data, time) => {
return (dispatch) => {
setTimeout(() => {
dispatch(createIncrementAction(data))
},time)
}
}
3.2.4 redux/reducer.js
import {INCREMENT,DECREMENT} from './constant'
const initState = 0
export default function countReducer (preState = initState, action) {//reducer函数会接到两个参数:之前的状态(preState),动作对象(action)
console.log(preState,action,'初始化');//0 {type: '@@redux/INIT2.0.y.s.0.h'}
const { type, data } = action
switch (type) {
case INCREMENT:
return preState + data
case DECREMENT:
return preState - data
default:
return preState
}
}
3.2.5 redux/store.js
import { createStore,applyMiddleware,combineReducers } from 'redux'
import countReducer from './reducer'
// 用于支持异步action
import thunk from 'redux-thunk'
//引入redux-devtools-extension
import {composeWithDevTools} from 'redux-devtools-extension'
//汇总reducer:实现数据共享
const allReducer = combineReducers({
he: countReducer,
rens:personReducer
})
// 暴露一个store对象
export default createStore(allReducer ,composeWithDevTools(applyMiddleware(thunk)))
4 react-redux
4.1 原理
4.2 编码
4.2.1 index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './redux/store'
import {Provider} from 'react-redux'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
{}
);