【React】@redux/toolkit

开始了新的项目,项目中使用了react-redux集成工具的使用,那必须要学习啦,发现相关的资料和视频还是不多的,所以一起学习, 高效掌握redux/toolkit的用法, 对应在b站会出一个语音教清晰的视频。

视频配合食用 暂时录制失败 太晚了 明天吧

1.安装

首先创建react一个项目,可以参考react项目

# Redux + TypeScript template
npx create-react-app my-app --template redux

通过node的npm安装

# NPM
npm install react-redux
npm install @reduxjs/toolkit

用Yarn的同学可以

# Yarn
yarn add @reduxjs/toolkit

2. 基本使用 { createSlice }

# cmd
mkdir store ( src下创建一个store文件 )
cd store
echo nul>index.js
mkdir features ( store下创建一个features )
cd features 
echo nul>counterSlice.js  ( features下创建counterSlice.js文件 )


2.1 counterSlice.js

// counterSlice.js
import { createSlice } from '@reduxjs/toolkit'

export const counterSlice = createSlice({
	name:"counter",
	initialState:{
		count:1,
		title:"i am counter title"
	}
})

reducers:{
	increment:(state, payload) => {
		state.count = state.count + 1 ;
	},
	decrement:(state, payload) => {
		state.count =state.count -1;
	}
}

export const { increment, decrement } = counterSlice.actions;

export default counterSlice.reducer;

2.2 index.js

import { configureStore } from '@reduxjs/toolkit'
import counter from "./features/counterSlice"

export default configStore({
	//创建一个redux数据
	reducer:{
		counter:counterSlice
	}
})

2.3 根目录 index.js

在跟目录index.js下通过react-redux中的Providerstore传递给所有的组件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from "react-redux";
import store from './store'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);


2.4 App.js 组件内使用state

import Test from "./pages/test";
import { useSelector, useDispatch } from "react-redux" ; // 有了hook就不用connect连接了
import { increment, decrement } from './store/features/counterSlice'
function App() {
  const { count } = useSelector(state => state.counter)
  const dispatch = useDispatch() // 用来调用reducer 
  return (
    <div className="App">
      <Test/>
      <button onclick={() => {
		dispatch(increment()}}>{count}</button>
    </div>
  );
}

export default App;

//遗留问题
export 和export default 的区别
features 含义:是用于帮助实现某种功能的具体工具, 即How to do。 例如,刹车碟片就是汽车用于实现刹车的功能的一个Feature。
react 函数的定义位置 和 this指向 .bind
fetch 使用

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值