【问题标题】:React: TypeError: dispatch is not a function反应:TypeError:调度不是一个函数
【发布时间】:2020-09-16 17:27:53
【问题描述】:

我想从 redux 中获取。我正在关注本教程:https://codesandbox.io/s/react-redux-application-hewdb?file=/src/pages/PostsPage.js

但是当我在我的代码中使用它时:

import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import {fetchInterview} from '../actions/interviewActions'

const DetailInterview = (props, { dispatch, loading, interviews, hasErrors }) => {

  console.log("test interview",interviews)
  useEffect(() => {
    const { match: { params: { id } } } = props;
    dispatch(fetchInterview(id))
  }, [dispatch])

  const interviewslist = interviews

  console.log('interview: ', interviews)

  return (
    <div>
      <h3>All participants</h3>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Interview id</th>
            <th>Partcipants id</th>
            <th>Time</th>
          </tr>
        </thead>
        <tbody>
          {
            console.log('interviews:sad ', interviews)
          }
          {
            interviews? interviews.map((interview) => {
              console.log('sadassad',interview)
              console.log('sadaghahhgsghssad',interviews)
              return (
                <tr key={interview.id}>
                  <td>{interview.id}</td>
                  <td>{interview.interview_id}</td>
                  <td>
                    {/* <Link to={`/posts/${post.id}`}> */}
                    {interview.participant_id}
                    {/* </Link> */}
                  </td>
                  <td>{interview.created_at}</td>
                </tr>
              ) 
            }) : null
          }
        </tbody>
      </table>
    </div>
  );
}

// export default DetailInterview;

const mapStateToProps = state => ({
  loading: state.interview.loading,
  interviews: state.interview.interview,
  hasErrors: state.interview.hasErrors,
})
export default connect(mapStateToProps)(DetailInterview)

我得到一个错误:Uncaught TypeError: dispatch is not a function

无法理解这背后的错误。

【问题讨论】:

  • React 组件有 1 个参数 props (const DetailInterview = (props) =&gt; ),即调用 props.dispatch
  • @NikitaMadeev 但我也需要这里需要的道具:const { match: { params: { id } } } = props;
  • 我不建议去掉,只是组件没有的第二个参数,从props调用dispatch,例如:const { dispatch } = props;
  • @NikitaMadeev 值在 mapStateToProps 中未存储。
  • 他们也进来props,就像dispatch一样

标签: javascript reactjs redux react-redux redux-thunk


【解决方案1】:

您正在从 DetailInterview 的第二个参数中解构值,而您应该从 props 执行此操作,因为 mapStateToProps 和 connect 的值可作为连接组件的 props 使用

const DetailInterview = (props) => {
    const { dispatch, loading, interviews, hasErrors } = props;
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2020-06-11
    • 2015-09-11
    • 1970-01-01
    相关资源
    最近更新 更多