一、下载依赖
npm install react-redux --save
npm isntall redux --save
npm install redux-thunk
二、创建redux文件目录
三、在stroe.js创建仓库
import { createStore, applyMiddleware, compose } from 'redux'
//处理redux的异步任务的中间件
import thunk from 'redux-thunk'
import reducer from './reducer'
const store = createStore(reducer, compose(
applyMiddleware(thunk),
(window as any).__REDUX_DEVTOOLS_EXTENSION__ && (window as any).__REDUX_DEVTOOLS_EXTENSION__()
))
export default store
四、在index项目入口文件引入store
import React from 'react';
import ReactDOM from 'react-dom';
import store from './redux/store'
import {Provider} from 'react-redux'
import {getAllName} from './redux/action/manage'
import App from './App';
store.dispatch(getAllName())
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
五、编写action
export const add = (count) => {
return (dispatch) => {
(() => {
console.log('123',count)
dispatch({
type : 'addCount',
count
})
})()
}
}
export const reduce = (count) => {
return (dispatch) => {
(() => {
dispatch({
type : 'reduceCount',
count
})
})()
}
}
六、编写reducer
const init = {
number: 0
}
export default (state = init, action) => {
console.log('aqwe',action)
switch (action.type) {
case 'addCount':
return {...state,number : action.count+1}
case 'reduceCount':
return {...state,number : action.count-1}
default:
return state
}
}
七、home组件中通过useSelector和useDispatch来操作redux
import React, { useEffect, useState,useRef ,useReducer} from "react";
import {add,reduce} from '../redux/action/count'
import {useSelector,useDispatch} from 'react-redux'
export default function Home() {
const count = useSelector(state => state.count.number);
const dispatch = useDispatch();
useEffect(() => {
console.log('123',count)
})
return (
<>
<span>{count}</span>
<button onClick={() => dispatch(reduce(count))}>-</button>
<button onClick={() => dispatch(add(count))}>+</button>
</>
);
}