简体   繁体   English

React钩子,功能组件和Redux

[英]React hooks, function components and Redux

React hooks makes it possible to use all React features such as component state and lifecycle methods without class declarations (just function components). React钩子可以使用所有React功能,例如组件状态和生命周期方法,而无需类声明(仅是函数组件)。 This reduces boilerplate, duplication and negotiates the use of bug-prone this keyword. 这样可以减少重复样板,减少重复并协商易于使用this关键字的bug。 Further it makes it easy to isolate and share common state-management logic across unrelated components, thanks to function composition. 此外,由于功能组合,它使得在不相关的组件之间隔离和共享通用状态管理逻辑变得容易。

However, hooks doesn't replace Redux by it's purpose of centralized and predictable state container. 但是,钩子并不能代替Redux来达到集中和可预测状态容器的目的。 Is it possible to connect React function components to Redux, as I want to embrace the functions only paradigm of future React and still use Redux? 是否可以将React函数组件连接到Redux,因为我只想接受未来React的函数范式而仍然使用Redux?

You can use the useSelector and useDispatch hooks introduced in react-redux v7.1 as a stable release. 您可以使用react-redux v7.1中引入的useSelectoruseDispatch挂钩作为稳定版本。 Here's the link: https://react-redux.js.org/next/api/hooks 这是链接: https : //react-redux.js.org/next/api/hooks

To answer your question: 要回答您的问题:

Is it possible to connect React function components to Redux? 是否可以将React函数组件连接到Redux?

yes, it is possible , there is no difference. 是的,有可能 ,没有区别。 Simple example: 简单的例子:

import { useState } from "react";
import { connect } from "react-redux";

const Foo = ({ bar, handleOnClick }) => {
  const [foo, setFoo] = useState(true);

  return (
    <div onClick={handleOnClick}>
      {foo}
      <div>{bar}</div>
    </div>
  );
};

const mapStateToProps = state => ({
  bar: state.bar
});

const mapDispatchToProps = dispatch => ({
  handleOnClick() {
    dispatch({ type: "foo" });
  }
});

export const FooContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(Foo);

Actually, you can see that in the Redux documentation intself: 实际上,您可以在Redux文档中看到以下内容:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM