[英]I can't access “this.props.match.params.id” in React.js
My parent component's code where I am setting up my props is this:-我设置道具的父组件代码是这样的:-
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}
/>
);
});
}
My parent component is working perfectly.我的父组件运行良好。
http://localhost:3000/anime/edit/5eb2f493091abc64b44bad23
BUT when I try to access the ID passed to my url, I am getting "undefined".但是当我尝试访问传递给我的 url 的 ID 时,我得到“未定义”。
Child Component's Code, where I am getting the error子组件的代码,我收到错误
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));
}
I want to access The ID in my url.我想访问我的 url 中的 ID。
UPDATE
The best option is probably to use useLocation hook. 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
You can wrap Your child component in withRouter
.您可以将您的子组件包装在
withRouter
中。 Someting like that有点像
import React from 'react'
import { withRouter } from 'react-router'
const MyChildComponent = (props) => {
// You can use props here
return <div />
}
export default withRouter(MyChildComponent)
The code snippet You provided doesn't seem to be complete, but props can only be accessed from inside of a react component.您提供的代码片段似乎并不完整,但只能从反应组件内部访问道具。
Alternatively, You can use a different way to extract the id from url.或者,您可以使用不同的方式从 url 中提取 id。 Something that doesn't include react-router.
不包括 react-router 的东西。 For example
例如
const path = window.location.pathname.split('/')
const id = path[path.length - 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.