首页 > 解决方案 > TypeError:调度不是 ReactJS 中的函数

问题描述

我是 React 的新手,正在尝试构建一个显示您输入的联系人的应用程序。虽然一切似乎都很好,但每次我尝试添加新联系人时,浏览器都会向我抛出这个错误。

在此处输入图像描述

这是我的Contacts.js

import React, { useContext } from "react";

import { Container, ListGroup, ListGroupItem, Spinner } from "reactstrap";
import Contact from "../components/Contact";
import { MdAdd } from "react-icons/md";
import { useHistory } from "react-router-dom";
import { ContactContext } from "../context/Context";
import { CONTACT_TO_UPDATE } from "../context/action.types";

const Contacts = () => {
  const { state, dispatch } = useContext(ContactContext);

  // destructuring contacts and isLoading from state
  const { contacts, isLoading } = state;

  // history hooks from react router dom to get history
  const history = useHistory();

  // handle fab icon button click
  // will set in state of the contact to update and send it to the contact/add route
  const AddContact = () => {
    //TODO: use dispatch to send user to add contact screen
    dispatch({                             //THE ERROR IS HERE!
      type: CONTACT_TO_UPDATE,
      payload: null,
      key: null
    });
    history.push("/contact/add");
  };

  // return loading spinner
  if (isLoading) {
    return (
      <div className="Center">
        <Spinner color="primary" />
        <div className="text-primary">Loading...</div>
      </div>
    );
  }

  return (
    <Container className="mt-4">
      {/* TODO: Loop through FIREBASE objects  */}
      {contacts.length === 0 && !isLoading ? (
        <div className="Center text-large text-primary">
          NO Contacts found in firebase
        </div>
      ) : (
        <ListGroup>
          {Object.entries(contacts).map(([key, value]) => (
            <ListGroupItem key={key}>
              <Contact contact={value} contactKey={key} />
            </ListGroupItem>
          ))}
        </ListGroup>
      )}
      <MdAdd className="fab icon " onClick={AddContact} />
    </Container>
  );
};

export default Contacts;

如果答案对初学者有点友好,那将非常有帮助。

标签: javascriptreactjsdispatch

解决方案


推荐阅读