介绍 React-Redux 使用 Hooks (useSelector && useDispatch)
介绍:
在阅读本文之前,您应该了解 React 和 Redux 及其工作原理。
本文是关于 React-Redux Hooks 的。我们将在本文中讨论以下要点:
* Redux 的钩子。
* 如何使用useDispatchHook。
* 如何使用useSelectorHook。
1. Redux 的 Hooks
在使用 Hooks 之前,我们总是使用connect()一个高阶组件和包装器来包装我们的组件,connect()从 Redux 存储中读取值。
connect()接受两个参数,均为可选:
mapStateToPropsmapDispatchToProps
- mapStateToProps:
每次存储状态改变时调用。它接收整个存储状态,并返回该组件所需数据的对象。
- mapDispatchToProps:
此参数可以是函数,也可以是对象。如果是函数,则会在组件创建时调用一次。它将接收 dispatch 作为参数,并返回一个包含使用 dispatch 来调度操作的函数的对象。
有关connect()的更多信息
让我们开始学习 React-Redux Hooks。React-Redux 现在提供了一组 Hook API,作为现有connect()高阶组件的替代方案。这些 API 允许您订阅 Redux Store 并调度操作,而无需将组件包装在其中connect()。通过将 Hook API 与函数组件结合使用,可以保持组件精简,代码也更加简洁。
钩子:
2. useDispatch():
useDispatch()hook 相当于mapDispatchToProps。
我们将调用useDispatch并将其存储到变量 中dispatch。此钩子会从 Redux 存储中返回一个 。您可以根据需要使用它来调度操作。reference我们 通过调用 dispatch 并传入操作创建者的返回值来调度它。dispatch function
如何使用
useDispatch下面是使用和的小组件useSelector
import React from "react";
//import useDispatch from react-redux
import { useDispatch} from "react-redux";
//these are actions define in redux>actions folder
import { updateFirstName } from "../redux/actions";
const Form = () => {
const dispatch = useDispatch();
const handleFirstName = () => {
//dispatching the action
dispatch(updateFirstName("Jason"));
};
return (
<React.Fragment>
<div className="container">
<button onClick={handleFirstName}>Update First
Name</button>
</div>
</React.Fragment>
);
};
export default Form;
GITHUB redux-hooks中的完整代码
3.useSelector():
useSelector()hook 相当于mapStateToProps
useSelector是一个函数,它将当前状态作为参数并返回您想要的任何数据,它允许您将返回值存储在功能组件范围内的变量中,而不是作为 props 传递
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { updateFirstName } from "../redux/actions";
const Form = () => {
const dispatch = useDispatch();
const nameObj = useSelector((state) => state.nameReducer);
const { firstName } = nameObj;
const handleFirstName = () => {
dispatch(updateFirstName("Jason"));
};
return (
<React.Fragment>
<div className="container">
<label>First Name : {firstName}</label>
<button onClick={handleFirstName}>Update First Name</button>
<label>Last Name : {lastName}</label>
<button type="submit" onClick={handleLastName}>
Update First Name
</button>
</div>
</React.Fragment>
);
};
export default Form;
GITHUB redux-hooks中的完整代码
使用Store():
useStore()hook 返回对传递到组件中的相同 Redux 存储的引用Provider。
此钩子可能不宜频繁使用。建议您优先使用 useSelector()。不过,对于需要访问 store 的不太常见的场景(例如替换 reducer),它或许会有所帮助。
import React from 'react'
import { useStore } from 'react-redux'
export const ExampleComponent = ({ value }) => {
const store = useStore()
// EXAMPLE ONLY! Do not do this in a real app.
// The component will not automatically update if the store state changes
return <div>{store.getState().obj.name}</div>
}
GITHUB redux-hooks中的完整代码
如果你想了解更多信息useDispatch,useSelector这里是官方链接React Redux Hooks
欢迎提出进一步的改进、建议或帮助。:)
文章来源:https://dev.to/bangash1996/introduction-react-redux-using-hooks-useselector-useddispatch-26ch
后端开发教程 - Java、Spring Boot 实战 - msg200.com