ReactJS:React-Router 将值传递给另一个页面 [英] ReactJS: React-Router pass value to another page
本文介绍了ReactJS:React-Router 将值传递给另一个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用 react-router 将值从一个页面传递到另一个页面.
I have need to pass a value from a page to another using react-router.
我试过这种方式:
<li>
<A
className="btn btn-link btn-sm"
href={{ pathname: Routes.detail_page, search: `?_id=${C.Code}`, state: this.props.current }}>
{ 'Open' }
</A>
</li>
我会将 this.props.current 传递给详细信息页面.
I would pass this.props.current to Detail Page.
在另一个页面中,如果我尝试在 componentDidMount() 中打印 this.props.current
它会导致未定义(当然在第一页中该值已参数化).
In the other page if I tried in the componentDidMount() to print this.props.current
it result undefined (of course in the first page this value is parametrized).
constructor(props){
super(props);
this.state = {
};
}
componentDidMount(){
let C = this.props.current
console.log("C is: ", C) // this is undefined
this.updateIsDeletableState()
}
我该怎么办?
推荐答案
你必须确保你在 Route
// file-where-you-define-routes.js
...
<Switch>
<Route path={`your-path/:id`} component={YourComponent} />
</Switch>
...
然后使用钩子useParams
获取参数
function YourComponent() {
const { id } = useParams();
let C = id;
console.log("C is: ", C) // this should be defined now
...
}
或者如果你使用类组件 this.props.match.params.id
OR if you use class component this.props.match.params.id
class YourComponent extends Component {
...
componentDidMount(){
let C = this.props.match.params.id; // match
console.log("C is: ", C) // this should be defined now
this.updateIsDeletableState()
}
}
这篇关于ReactJS:React-Router 将值传递给另一个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文