web前端全系列 教程
1839个小节阅读:2243.2k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
useSelector
useSelector
这个 hooks 让我们的组件从 Redux 的 store 状态树中提取它需要的任何数据。
src/features/counter/Counter.js
xxxxxxxxxx
import { useSelector } from 'react-redux';
import {
selectCount
} from './counterSlice';
const count = useSelector(selectCount);
srcfeatures/counter/counterSlice.js
xxxxxxxxxx
// selector 函数允许我们从 state 中获取值
// Selectors 也可以在使用的地方内联的方式定义
// 而不是仅仅只能在 slice 文件中。例如 : `useSelector((state) => state.counter.value)`
export const selectCount = state => state.counter.value
我们可以直接在组件文件当中,这么去获取数据:
xxxxxxxxxx
const count = useSelector(state => state.counter.value);
使用useDispatch来dispatch action
src/features/counter/Counter.js
xxxxxxxxxx
import { useDispatch } from 'react-redux';
import {
increment
} from './counterSlice';
<button
className={styles.button}
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
+
</button>
xxxxxxxxxx
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';
import reportWebVitals from './reportWebVitals';
import './index.css';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);