[英]Is there a way to use react-redux (useDispatch) in react using class based components? I am using useDispatch inside render function
Error: Invalid hook call.错误:无效的挂钩调用。 Hooks can only be called inside of the body of a function component.
钩子只能在 function 组件的主体内部调用。 This could happen for one of the following reasons:
这可能由于以下原因之一而发生:
Hooks are intended to be used in Functional components only.挂钩仅用于功能组件。 As per the Rules of hooks they can be called from
根据钩子规则,它们可以从
In order to other question为了其他问题
Is there a way to use react-redux (useDispatch) in react using class based components?
有没有办法使用 react-redux (useDispatch) 使用基于 class 的组件进行反应?
Yes, there are ways of using react-redux inside class based components.是的,有一些方法可以在基于 class 的组件中使用 react-redux。 Using connect API provided by
react-redux
library which will inject the action creators into the class component.使用
react-redux
库提供的连接API 将动作创建者注入 class 组件。 Eventually accessing the required dispatch
function by this.props
.最终通过 this.props 访问所需的
dispatch
this.props
。 You can have a look here for a basic example of how it can be used.您可以在这里查看如何使用它的基本示例。
Hope this helps.希望这可以帮助。
You cannot use hooks with class components.您不能将挂钩与 class 组件一起使用。 As written in the docs , you need to create a container/wrapper component that passes the actions.
如文档中所写,您需要创建一个传递操作的容器/包装器组件。
For that you have to use connect
from 'react-redux' like this:为此,您必须像这样使用“react-redux”中的
connect
:
import { connect } from 'react-redux'
const mapDispatchToProps = dispatch => {
return {
onTodoClick: id => {
dispatch(toggleTodo(id))
}
}
}
const VisibleTodoList = connect(mapStateToProps (HERE NOT NEEDED; IF YOU WANT TO DISPATCH ONLY), mapDispatchToProps)(TodoList)
export default VisibleTodoList
This would pass onTodoClick
to your component via props which you can just call like any prop: this.props.onTodoClick()
这将通过道具将
onTodoClick
传递给您的组件,您可以像任何道具一样调用它: this.props.onTodoClick()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.