首页 > 解决方案 > TypeError:this.props.match 在组件中未定义

问题描述

所以我正在创建一个仪表板,以便用户可以编辑记录和类似的东西。

我创建了编辑和删除按钮,它们转到各自的路线。

edit但是,我在组件上得到以下信息

TypeError: this.props.match is undefined

这是我的编辑文件

import React, { Component } from "react";
import axios from "axios";
import swal from "sweetalert";

import AuthService from "../../Auth/AuthService";
import withAuth from "../../Auth/withAuth";
const Auth = new AuthService();

class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      collection: {},
      categorys: []
    };
  }

  componentDidMount() {
    const collectionId = this.props.match.params.id;
    axios
      .get("/api/collections/" + collectionId)
      .then(result => {
        this.setState({ collection: result.data });
      })
      .catch(error => {
        console.log(error);
      });

    axios
      .get("/api/category")
      .then(res => this.setState({ categorys: res.data }))
      .catch(error => {
        console.log(error);
      });
  }

  onChange = e => {
    const state = this.state.collection;
    state[e.target.name] = e.target.value;
    this.setState({ collection: state });
  };

  onSubmit = e => {
    e.preventDefault();
    const collectionId = this.props.match.params.id;
    const {
      title,
      description,
      reference,
      images,
      price,
      year,
      category
    } = this.state.collection;

    let config = {
      headers: { Authorization: "bearer " + Auth.getToken() }
    };

    let body = {
      title,
      description,
      reference,
      images,
      price,
      year,
      category
    };

    axios
      .put("/api/collections/" + collectionId, body, config)
      .then(result => {
        this.props.history.push("/collections/" + collectionId);
      })
      .catch(error => {
        swal({
          title: "Error",
          text: `${error}`,
          icon: "error",
          button: "Try again"
        });
      });
  };

  render() {
    return (
      <>
        <div className='block md:flex md:flex-column h-full'>
          <div className='p-12 w-full text-center text-gray-800'>
            <h1 className='title mb-10'>Edit A collection</h1>

            <form className='w-full m-auto max-w-lg' onSubmit={this.onSubmit}>
              <div className='flex flex-wrap mb-4'>
                <label htmlFor='title'>Title:</label>
                <input
                  type='text'
                  name='title'
                  value={this.state.collection.title}
                  onChange={this.onChange}
                  placeholder='Title'
                />
              </div>

              <div className='flex flex-wrap'>
                <label htmlFor='description'>Description:</label>
                <textarea
                  type='text'
                  name='description'
                  className='h-64'
                  value={this.state.collection.description}
                  onChange={this.onChange}
                  placeholder='Content'
                ></textarea>
              </div>

              <div className='flex flex-wrap mb-4'>
                <label htmlFor='reference'>Reference:</label>
                <input
                  type='text'
                  name='reference'
                  value={this.state.collection.reference}
                  onChange={this.onChange}
                  placeholder='reference'
                />
              </div>

              <div className='flex flex-wrap mb-4'>
                <label htmlFor='description'>images:</label>
                <input
                  type='file'
                  multiple
                  name='content'
                  value={this.state.images}
                  onChange={this.onChange}
                ></input>
              </div>

              <div className='flex flex-wrap mb-4'>
                <label htmlFor='price'>Price:</label>
                <input
                  type='number'
                  name='price'
                  value={this.state.collection.price}
                  onChange={this.onChange}
                  placeholder='price'
                />
              </div>

              <div className='flex flex-wrap mb-4'>
                <label htmlFor='year'>Year:</label>
                <input
                  type='number'
                  name='year'
                  value={this.state.collection.year}
                  onChange={this.onChange}
                  placeholder='Year'
                />
              </div>

              <div className='flex flex-col mb-2'>
                <label htmlFor='category'>Category</label>

                <div className='relative'>
                  <select
                    id='category'
                    value={this.state.collection.category}
                    onChange={this.onChange}
                  >
                    <option>N/A</option>
                    {this.state.categorys.map(category => (
                      <option key={category._id} value={category.name}>
                        {category.name}
                      </option>
                    ))}
                  </select>

                  <div className='pointer-events-none absolute inset-y-0 right-0 flex items-center px-2'>
                    <svg
                      className='fill-current h-4 w-4'
                      xmlns='http://www.w3.org/2000/svg'
                      viewBox='0 0 20 20'
                    >
                      <path d='M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z' />
                    </svg>
                  </div>
                </div>
              </div>
              <div className='flex'>
                <button type='submit' className='btn w-full'>
                  Submit
                </button>
              </div>
            </form>
          </div>
        </div>
      </>
    );
  }
}

export default withAuth(Edit);

如果我将鼠标悬停在仪表板中的编辑链接上,则会显示 ID,但是,在编辑页面上,查找集合的 ID 似乎有问题。

标签: javascriptreactjs

解决方案


找到对象没有问题idmatch不是路由的直接子组件的组件需要使用withRouterhoc 来访问match对象:

export default withRouter(withAuth(Edit));

推荐阅读