javascript - 我无法在 React.js 中访问“this.props.match.params.id”
问题描述
我设置道具的父组件代码是这样的:-
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));
}
我想访问我的网址中的 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。不包括反应路由器的东西。例如
const path = window.location.pathname.split('/')
const id = path[path.length - 1]
推荐阅读
- javascript - 在 Javascript 中删除和克隆 DOM 元素
- java - 代码完成停止为“Java 扩展包”工作
- selenium - Selenium 抓取 JS 加载的页面
- puppet - 在 Puppet 5 中循环导致重复声明错误
- python - Python 和 PostgreSQL - 检查多插入操作
- c++ - 在类的私有部分声明一个数组,并在构造函数中分配数组值
- ios - 使用 Swift IOS 语言通过蓝牙发送信息
- javascript - 计算页面上具有 id 属性的列表元素的数量
- javascript - 如何在元素或弹出窗口中隐藏/显示部分 onclick
- python - 如何使用 map 函数将数据框中的所有负数转换为 python pandas 中所有数字的平均值?