简体   繁体   English

如何使用 Z1E35BCBA2DBA10897C7BD0805D451 在 CLASS 反应组件中获取 redux 存储或 redux 调度

[英]How to get redux store or redux dispatch in CLASS react component using typescript

I know how to to dispatch and get store using functional component.我知道如何使用功能组件调度和获取商店。 There is a great documentation about it here 这里有一个很好的文档

But what about class component?但是 class 组件呢? How to get store and fire dispatch using class component.如何使用 class 组件获取存储和消防调度。 There is nothing said about it.没有什么说的。

Lets say I defined hooks.ts:假设我定义了 hooks.ts:

import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import { RootState, AppDispatch } from './store/store';

export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

And I need this functional component make as class:我需要这个功能组件作为 class:

import {useAppDispatch, useAppSelector} from "../../../hooks"
import { setRelease } from "./../store/factorySlice/factorySlice"
const X: React.FC = () => {
  const {selectedRelease} = useAppSelector(store => store.factory)
  const dispatch = useAppDispatch()

  return (
    <>
     {selectedRelease}
     <button onClick={() => dispatch(setRelease())}>Click</button>
    </>
  )
}

Redux Toolkit is our official recommended approach for writing Redux logic. Redux Toolkit是我们官方推荐的编写 Redux 逻辑的方法。 It wraps around the Redux core , and contains packages and functions that we think are essential for building a Redux app包含Redux内核,并包含我们认为对于构建 Redux 应用程序至关重要的包和功能

You can use it with class component by using react-redux 's connect API:您可以通过使用react-reduxconnect API 将其与 class 组件一起使用:

import { connect } from "react-redux";
import { setRelease } from "./../store/factorySlice/factorySlice"

class X extends React.Component {
  render() {
    return (
      <>
        {this.props.selectedRelease}
        <button onClick={() => this.props.dispatch(setRelease())}>Click</button>
      </>
    );
  }
}

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

export default connect(mapStateToProps)(X);

This was the first implementation.这是第一次实施。 You would connect the class component to the store like您可以将 class 组件连接到商店,例如

connect()(MyComponent)连接()(我的组件)

Where Class is MyComponent其中 Class 是 MyComponent

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

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