[英]ReactJS: React-Router pass value to another page
I have need to pass a value from a page to another using react-router.我需要使用 react-router 将一个页面的值传递到另一个页面。
I have tried in this way:我试过这样:
<li>
<A
className="btn btn-link btn-sm"
href={{ pathname: Routes.detail_page, search: `?_id=${C.Code}`, state: this.props.current }}>
{ 'Open' }
</A>
</li>
I would pass this.props.current to Detail Page.我会将 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).在另一页中,如果我尝试在 componentDidMount() 中打印
this.props.current
它会导致未定义(当然在第一页中这个值是参数化的)。
constructor(props){
super(props);
this.state = {
};
}
componentDidMount(){
let C = this.props.current
console.log("C is: ", C) // this is undefined
this.updateIsDeletableState()
}
How can I do?我能怎么做?
You have to make sure that you have defined URL parameter in the Route
您必须确保已在
Route
中定义了 URL 参数
// file-where-you-define-routes.js
...
<Switch>
<Route path={`your-path/:id`} component={YourComponent} />
</Switch>
...
Then use hook useParams
to get the parameter然后使用钩子
useParams
获取参数
function YourComponent() {
const { id } = useParams();
let C = id;
console.log("C is: ", C) // this should be defined now
...
}
OR if you use class component this.props.match.params.id
或者,如果您使用 class 组件
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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.