[英]How to access component parameters from app.js in react router
我有一個反應應用程序,其中反應路由器在 App.js 中初始化。 當 url 為localhost:3000/id
,Home 組件將呈現給 App.js,但我需要從 App.js 獲取id
變量以運行initBusinessDetails()
如何從 App 訪問id
變量.js。
App.js 代碼
import React from 'react'
import axios from 'axios';
import ReactLoading from 'react-loading';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getBusiness } from './actions/GetBusinessDetails';
import Home from './components/Home';
import Categories from './components/Categories';
class App extends React.Component {
initBusinessDetails(){
console.log(this.props)
const { params } = this.props.match
axios.get(`http://localhost:8081/getBusiness?businessId=`+params.id)
.then(res => {
this.props.getBusiness(res.data)
})
}
componentDidMount(){
this.initBusinessDetails();
}
render() {
return (
<div>
{!this.props.business ?
<div>
<ReactLoading type="bars" color="#000"/>
</div>:
<div>
<Router>
<Route exact path="/:id" component={Home}/>
<Route exact path="/:id/categories" component={Categories}/>
</Router>
</div>
}
</div>
)
}
}
function mapStateToProps(state){
return{
business:state.business
}
}
function matchDispatchToProps(dispatch){
return bindActionCreators({getBusiness : getBusiness},dispatch)
}
export default connect(mapStateToProps,matchDispatchToProps)(App)
訪問匹配參數
在來自react-router-dom
的component
道具下渲染的component
也會收到match
道具。
您將可以訪問各個位置的匹配對象:
- 路由組件為 this.props.match
- 路由渲染為 ({ match }) => ()
- 將孩子路由為 ({ match }) => ()
- withRouter 作為 this.props.match
- matchPath 作為返回值
要從中訪問id
:
initBusinessDetails() {
const { params } = this.props.match;
axios.get(`http://localhost:8081/getBusiness?businessId=${params.id}`)
.then(res => {
this.props.getBusiness(res.data)
});
}
但此代碼在我的路由器之外
現在這段代碼在你的路由器之外,所以你需要在你的路由器內部渲染一些可以調用該函數的東西。 這很容易,因為您仍然只使用Router
因此會呈現所有匹配的路由(與只返回第一個匹配路由的Switch
相反)。 使用內聯功能組件渲染另一條路線。 也可以基於類,但需要進行調整才能工作。 如果是這種情況,請告訴我。
<Route
exact
path="/:id"
component={({ match }) => {
// add any logic here to do anything when this component is
// mounted/rendered, like call `initBusinessDetails` with
// the `id` param
return null; // return nothing to the UI
}}
/>
現在,每當路由器重新渲染該路由時,這都會觸發該功能,因此您可能需要在App
和 axios 調用中添加邏輯輸出以確保您只初始化一次。 如果您可以使用鈎子,那么內聯函數組件中的useEffect
鈎子就可以解決問題。
initBusinessDetails(id) {
axios.get(`http://localhost:8081/getBusiness?businessId=${id}`)
.then(res => {
this.props.getBusiness(res.data)
});
}
...
<Route
exact
path="/:id"
component={({ match }) => {
useEffect(
() => initBusinessDetails(match.params.id),
[] // call only once when mounted
);
return null; // return nothing to the UI
}}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.