更新类别时出现 TypeError: Cannot read property 'params' of undefined。

3

基本上我正在尝试创建一个代码,允许我使用参数更新slug。

不知道为什么我的代码会抛出这个错误。

"TypeError:在React中无法读取未定义的属性'params'。"

我尝试替换

useEffect(() => {
    loadCategory();
  }, []);

使用

useEffect(() => {
  if(match.params.slug) loadOrders()
}, [match.params.slug])

但它仍然无法正常工作。

这是我编写的代码。

    import React, { useState, useEffect } from "react";
import {
  HistoryContainer,
  HistoryBg,
  TextContainer2,
  TextContainer3,
  Text,
  CatForm,
  FormLabel,
  FormControl,
  ButtonPrimary,
} from "./CategoryUpdateElements";
import AdminNav from "../AdminNav/index";
import { toast } from "react-toastify";
import { useSelector } from "react-redux";
import { getCategory, updateCategory } from "../../../functions/category";

const CategoryUpdate = ({ history, match }) => {
  const { user } = useSelector((state) => ({ ...state }));

  const [name, setName] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    loadCategory();
  }, []);

  const loadCategory = () =>
    getCategory(match.params.slug).then((c) => setName(c.data.name));

  const handleSubmit = (e) => {
    e.preventDefault();
    // console.log(name);
    setLoading(true);
    updateCategory(match.params.slug, { name }, user.token)
      .then((res) => {
        // console.log(res)
        setLoading(false);
        setName("");
        toast.success(`"${res.data.name}" is updated`);
        history.push("/admin/category");
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
        if (err.response.status === 400) toast.error(err.response.data);
      });
  };

  return (
    <>
      <HistoryContainer>
        <HistoryBg>
          <AdminNav />
          <TextContainer2>
            <TextContainer3>
              {loading ? <Text>Loading..</Text> : <Text>Update category</Text>}
              <CatForm onSubmit={handleSubmit}>
                <FormLabel>Name</FormLabel>
                <FormControl
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  autoFocus
                  required
                />
                <ButtonPrimary>Save</ButtonPrimary>
              </CatForm>
            </TextContainer3>
          </TextContainer2>
        </HistoryBg>
      </HistoryContainer>
    </>
  );
};

export default CategoryUpdate;

更新:

为了更好地理解这个问题,这段代码让我更新slug的名称,但是TypeError不让我这样做。实际上,我在按照教程操作,但显然他的代码可以工作。我确信我已经按照他的要求写了代码,唯一的区别是我的用户界面。

我也尝试过控制台记录match,并检查它,结果是我看到了"undefined",这并不令人惊讶... 它应该向我显示slug,但却给了我"undefined"。

这是他的代码,允许他更新自己的slug。

import React, { useState, useEffect } from "react";
import AdminNav from "../../../components/nav/AdminNav";
import { toast } from "react-toastify";
import { useSelector } from "react-redux";
import { getCategory, updateCategory } from "../../../functions/category";

const CategoryUpdate = ({ history, match }) => {
  const { user } = useSelector((state) => ({ ...state }));

  const [name, setName] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    loadCategory();
  }, []);

  const loadCategory = () =>
    getCategory(match.params.slug).then((c) => setName(c.data.name));

  const handleSubmit = (e) => {
    e.preventDefault();
    // console.log(name);
    setLoading(true);
    updateCategory(match.params.slug, { name }, user.token)
      .then((res) => {
        // console.log(res)
        setLoading(false);
        setName("");
        toast.success(`"${res.data.name}" is updated`);
        history.push("/admin/category");
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
        if (err.response.status === 400) toast.error(err.response.data);
      });
  };

  const categoryForm = () => (
    <form onSubmit={handleSubmit}>
      <div className="form-group">
        <label>Name</label>
        <input
          type="text"
          className="form-control"
          onChange={(e) => setName(e.target.value)}
          value={name}
          autoFocus
          required
        />
        <br />
        <button className="btn btn-outline-primary">Save</button>
      </div>
    </form>
  );

  return (
    <div className="container-fluid">
      <div className="row">
        <div className="col-md-2">
          <AdminNav />
        </div>
        <div className="col">
          {loading ? (
            <h4 className="text-danger">Loading..</h4>
          ) : (
            <h4>Update category</h4>
          )}
          {categoryForm()}
          <hr />
        </div>
      </div>
    </div>
  );
};

导出默认的 CategoryUpdate;

我还是编程新手,希望大家能够帮帮我 ^_^


请展示一下在 Route 组件内如何使用 CategoryUpdate。 - Oro
1
这意味着你的 match 对象是空的并且是 undefined。尝试在控制台中输出它,并检查是否正确传递。 - threeFatCat
1个回答

3
我认为您遇到的问题与获取作为props的match有关。如果您在处理match props时遇到问题,请尝试使用useRouteMatch代替。
import { useRouteMatch } from "react-router-dom";

function YourComponent() {
  let match = useRouteMatch();

  // Do whatever you want with the match...

  return <div />;
}

我认为这更方便易用。 查看更多示例


谢谢你的回答,Qodir!我会尝试一下 :) - Patrisho
不客气。我正在我的真实项目中使用它,它非常方便。 - Qodir Amirov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接