【问题标题】:Redux Thunk not firing return statementRedux Thunk 没有触发返回语句
【发布时间】:2019-05-30 06:30:24
【问题描述】:

我在 Stackover 流程​​中看到过这样的问题,但似乎都没有解决我的问题。我正在尝试使用 redux thunk 调度一个操作,但不幸的是,我的 thunk 函数没有触发 return 语句。

我已经尝试过像往常一样使用 redux thunk:

export function handleLikeThunk(id, likeType){
  console.log('thunk1')
  return (dispatch) => {
    console.log('thunk2', id);

  }
}

但是,代码只能到达“thunk1”消息。它从不显示“thunk2”

我正在尝试处理一个like按钮,所以首先我导入了redux thunk函数:

import { handleLikeThunk } from '../redux/actions/posts';

我有一个函数,只要按下赞按钮,就会调用 thunk:

handleLike = (e) => {

    const { likes, id } = this.state

    if(e.target.getAttribute('name') === 'upVote'){
      this.setState((perviouState)=>({
        likes: perviouState.likes + 1
      }));

      handleLikeThunk(id, 'upVote');

    }
    if(e.target.getAttribute('name') === 'downVote' && likes > 0){
      this.setState((perviouState)=>({
        likes: perviouState.likes - 1
      }));

      handleLikeThunk(id, 'downVote');

    }

 }

为了做到这一点,我将我的组件连接到商店

const mapDispatchToProps = (dispatch) => {
  return { 
    handleLikeThunk: (id, likeType) => dispatch(handleLikeThunk(id, 
likeType)) 
   }
  }

export default connect(null, mapDispatchToProps)(Post)

就像我说的,我希望能够使用 thunk 函数在后端发布此信息,但它永远不会进入 thunk 函数内的返回状态。

【问题讨论】:

    标签: reactjs react-redux redux-thunk


    【解决方案1】:

    看起来您调用的是原始函数,而不是您放入 mapDispatchToProps 的函数,请尝试将 handleLikeThunk(id, 'upVote'); 更改为 this.props.handleLikeThunk(id, 'upVote');

    【讨论】:

    • 发生在我身上的次数已经够多了,很高兴我不是唯一犯这个错误的人。如果解决了问题,请务必将答案标记为已接受
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2021-06-03
    • 2019-01-27
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多