【问题标题】:I can't access "this.props.match.params.id" in React.js我无法在 React.js 中访问“this.props.match.params.id”
【发布时间】:2020-05-06 18:05:44
【问题描述】:

我设置道具的父组件代码是这样的:-

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

但是当我尝试访问传递给我的网址的 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));
  }

我想访问我的网址中的 ID。

【问题讨论】:

    标签: javascript reactjs url frontend react-router-dom


    【解决方案1】:

    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)
    

    你提供的代码 sn-p 好像不完整,但是 props 只能从 react 组件内部访问。

    或者,您可以使用不同的方式从 url 中提取 id。不包括反应路由器的东西。例如

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

    【讨论】:

      猜你喜欢
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2020-06-14
      • 2017-12-11
      相关资源
      最近更新 更多