【问题标题】:Explain this problem with dispatch() and connect() in redux?用redux中的dispatch()和connect()解释这个问题?
【发布时间】:2019-11-08 22:02:17
【问题描述】:

我正在观看本教程,并且下面的代码在视频中完美运行,但是当我尝试它时,我收到“未定义调度”错误。这是为什么呢?

import React from 'react'
import {connect} from 'react-redux'
import {removeExpense} from '../Actions/Actions'

const ListItem = ({id, description, note, amount, createdAt})=>(
    <div>
        <h5>{description}</h5>
        <p>Note: {note}</p>
        <p>Amount: {amount}</p>
        <p>Created @{createdAt}</p>
        <button onClick={()=>{dispatch(removeExpense(id))}}>remove</button>
        <br/>
    </div>
)

export default connect()(ListItem); //Just to inject dispatch() 

导师使用的是redux v3.7.2,react-redux v5.0.5 react v15。 现在我知道,如果我按照下面的方法处理它,我可以解决问题。

const ListItem = (props)=>(
    <div>
        <h5>{props.description}</h5>
        <p>Note: {props.note}</p>
        <p>Amount: {props.amount}</p>
        <p>Created @{props.createdAt}</p>
        <button onClick={()=>{props.dispatch(removeExpense(props.id))}}>remove</button>
        <br/>
    </div>
)

为什么删除按钮在第一个代码中不起作用?会不会是库的过时版本?

【问题讨论】:

  • 我很惊讶代码在视频中运行,正如您在此处显示的那样。一定有什么不同,因为我预计您会得到确切的错误。
  • 您能提供您正在观看的视频的链接吗?

标签: reactjs react-redux jsx


【解决方案1】:

您可以通过更改此行来修复您的第一个示例:

const ListItem = ({id, description, note, amount, createdAt})=>(

const ListItem = ({id, description, note, amount, createdAt, dispatch})=>(

【讨论】:

  • 这解决了问题。显然我正在观看的视频也是如此,我看了 100 遍,但不知何故我错过了。谢谢
【解决方案2】:

在你解构 props 时,你省略了应该被传递的调度。

或者将它添加到你的解构语句中:

const ListItem = ({id, description, note, amount, createdAt, dispatch})=>(

或通过props访问它

<button onClick={()=>{props.dispatch(removeExpense(id))}}>remove</button>

【讨论】:

  • 请注意,通过props 访问需要声明props。一种方法是 OP 在他的第二个示例中如何显示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2022-07-04
  • 2013-04-24
  • 1970-01-01
相关资源
最近更新 更多