redux系列文章目录
第三章 redux和react-redux,@reduxjs/toolkit依赖结合使用
前言
本章将使用react-redux,@reduxjs/toolkit依赖创建一个简单cout计数页面
准备工作
准备一个react框架的环境
bash
npx create-react-app react-redux-template
下载依赖
bash
npm i react-redux @reduxjs/toolkit
启动命令
bash
npm start
准备目录文件,
页面:src/pages/count/index.js
redux的存放:src/redux/store.js和src/redux/counterReducer.js
详情代码
store.js
bash
import { configureStore } from "@reduxjs/toolkit";
import countReducer from "./countReducer";
const store = configureStore({
reducer: {
counter: countReducer,
},
})
export default store;
counterReducer.js
bash
import { createSlice } from "@reduxjs/toolkit";
const countSlice = createSlice({
name: "counter",
//这里initialState一定到放对象object,不然报错
initialState: {value: 0},
reducers: {
increment: (state) => {
state.value +=1
},
decrement: (state) => {
state.value-=1
}
},
}
)
export const {increment, decrement} = countSlice.actions
export default countSlice.reducer
count/index.js
bash
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { increment, decrement } from '../../redux/countReducer'
export default function CountPage() {
const count = useSelector(state => state.counter.value)
const dispatch = useDispatch()
return (
<div>
<br />
<br />count:{count}
<br />
<button onClick={() => {
dispatch(increment())
}}>加+1</button>
<button onClick={() => { dispatch(decrement()) }}>减-1</button>
</div>
)
}
src/index.js
bash
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
// import App from './App';
import CountPage from './pages/count';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import store from './redux/store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<CountPage />
</Provider>
</React.StrictMode>
);
reportWebVitals();
提示:<Provider>很重要,引入store,这样整个应用都可以使用store相关hooks拿取数据
效果
react-redux存储状态