Redux Hooks使用方式

BB is nothing,show me the code。react

新公司学习阶段,代码大多数是使用redux来作状态管理,而且使用Hooks。虽然以前了解,可是没有在实际项目中使用过。写一个小的Demo 供你们参考。redux

React Redux在19年6月11日发不了的7.1版中提供了对Hooks的支持(以前大可能是使用一个redux-react-hook来作)。这咱们就能够不使用高阶HOC的方式了。ide

具体什么是Hook我就不介绍了,不懂的请自行查看react官方文档。函数

react-redux 提供了两个Hook用来替代connect。

useSelector

useSelector是链接mapStateToProps的替代方法。向其传递了一个函数,该函数使用Redux的存储状态并返回所需的状态。学习

useDispatch

useDispatch替换connect的mapDispatchToProps。它所作的只是返回store的dispatch方法,所以咱们能够手动调用dispatch。spa

直接一个对比的demo更明显code

Connect 组件

import React from "react";
import { connect } from "react-redux";
import { addCount } from "./store/counter/actions";
 
export const Demo = ({ count, addCount }) => {
  return (
    <div>
      <div>Count: {count}</div>
      <button onClick={addCount}>Count</button>
    </div>
  );
};
 
const mapStateToProps = state => ({
  count: state.counter.count
});
const mapDispatchToProps = { addCount };

// content 连接
export default connect(mapStateToProps, mapDispatchToProps)(Demo);复制代码

Hooks组件

import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { addCount } from './store/counter/actions'

export const Demo = () => {
  const count = useSelector(state => state.counter.count)
  const dispatch = useDispatch()

  return (
    <div>
      <div>Count: {count}</div>
      <button onClick={() => dispatch(addCount())}>Count</button>
    </div>
  )
}复制代码

可见Hooks的写法仍是特别简洁的。文档

相关文章
相关标签/搜索