[英]How get the value of {match.params.id} on react router
this is my code example but I do not know how to take the value and after use it这是我的代码示例,但我不知道如何取值和使用后
class View extends Component { componentDidMount() { var id = {match.params.id} } render() { return( <Router> <div> <Route path="/View/:id" component={Child}/> </div> </Router> ) } }
This might help you.这可能对你有帮助。 Just create constructor ie
constructor(props) {}
and inside it declare the id
as a state
variable to the class.只需创建构造函数,即
constructor(props) {}
并在其中将id
声明为类的state
变量。 Pass the value of match.params.id
to the id
by using id: this.props.match.params.id
.使用
id: this.props.match.params.id
将match.params.id
的值match.params.id
给id
。
Now u can access the state variable anywhere in your code and hope it solves your problem.现在您可以在代码中的任何位置访问状态变量,并希望它能解决您的问题。
class View extends Component {
constructor(props){
super(props);
this.state = {
id : this.props.match.params.id
}
}
componentDidMount() {
var id = {this.state.id}
}
render() {
return(
<Router>
<div>
<Route path="/View/:id" component={Child}/>
</div>
</Router>
)
}
}
尝试这个:
<Route path=`/View/${id}` component={Child}/>
Look here:看这里:
https://github.com/reactjs/react-router-tutorial/tree/master/lessons/06-params https://github.com/reactjs/react-router-tutorial/tree/master/lessons/06-params
You component will be injected a prop params
which you'll be able to get to like this:您的组件将被注入一个道具
params
,您将能够像这样:
<div>
<h2>{this.props.params.id}</h2>
</div>
You can do it this way :你可以这样做:
import { useParams } from 'react-router-dom';
function GetId() {
const { id } = useParams();
console.log(id);
return (
<div>
your expected id : {id}
</div>
);
}
{match.params.id} like variable. {match.params.id} 像变量。
this.id = this.props.match.params.id; this.id = this.props.match.params.id;
this.apartament = json.find((entry) => entry.id === this.id); this.apartament = json.find((entry) => entry.id === this.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.