簡體   English   中英

我無法在 React.js 中訪問“this.props.match.params.id”

[英]I can't access “this.props.match.params.id” in React.js

我設置道具的父組件代碼是這樣的:-

import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";

const Anime = (props) => (
  <tr>
    <td> {props.anime.animeName}</td>
    <td>
      <Link to={"/anime/edit/" + props.anime._id}>
        <button type="button" class="btn btn-primary">Edit</button>
      </Link>
    </td>
   </tr>
); 

animeList() {
    return this.state.animes.map((animeObject) => {
      return (
        <Anime
          anime={animeObject}
          key={animeObject._id}
        />
      );
    });
  }

我的父組件運行良好。

http://localhost:3000/anime/edit/5eb2f493091abc64b44bad23

但是當我嘗試訪問傳遞給我的 url 的 ID 時,我得到“未定義”。

子組件的代碼,我收到錯誤

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

  onSubmit(event) {
    event.preventDefault();
    const anime = {
      animeName: this.state.animeName,
    };

    console.log("The ID is ", this.props.match.params.id) // getting UNDEFINED

    axios
      .put("http://localhost:4000/animes/update/" + this.props.match.params.id, anime)
      .then((res) => console.log(res.data))
      .catch((err) => console.log(err));
  }

我想訪問我的 url 中的 ID。

UPDATE最好的選擇可能是使用 useLocation 鈎子。

import React from 'react'
import { useLocation } from 'react-router'

const MyChildComponent = (props) => {
  const location = useLocation()

  // You can location object
  return <div />
}

export default MyChildComponent

您可以將您的子組件包裝在withRouter中。 有點像

import React from 'react'
import { withRouter } from 'react-router'

const MyChildComponent = (props) => {
  // You can use props here
  return <div />
}

export default withRouter(MyChildComponent)

您提供的代碼片段似乎並不完整,但只能從反應組件內部訪問道具。

或者,您可以使用不同的方式從 url 中提取 id。 不包括 react-router 的東西。 例如

const path = window.location.pathname.split('/')
const id = path[path.length - 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM