[英]passing data between children in react-router
我有個問題。 問題是我需要以某種方式從 ReadProducts 組件中獲取產品 id 並將其傳遞給 ReadOne 組件,因為我無法在函數中獲取 id 並且無法顯示產品。 我怎樣才能做到這一點?
結構如下:
此組件是產品的父級,獲取所有並獲取一個
class Product extends Component {
render() {
return (
<Switch>
<Route path='/products' component={ReadProducts} />
<Route path='/products/:id' component={ReadOne} />
</Switch>
)
}
};
這是從 api 獲取所有產品
class ReadProducts extends Component {
constructor(props) {
super(props);
this.state = {
products: []
}
this.getProduct = this.getProduct.bind(this);
}
render() {
const { products } = this.state;
return(
<ul>
{
products.map(product => (
<li key={product.id}>
<Link to={`/products/${product.id}`}><button onClick={???}>{product.name}</button></Link>
</li>
))
}
</ul>
)
}
}
這是用於閱讀一種產品
class ReadOne extends Component {
constructor(props) {
super(props);
this.state = {
id: 0,
...
}
}
render() {
return(
<div className='pew'>
{this.state.name}, {this.state.id}...
</div>
)
}
}
問題是我需要以某種方式從 ReadProducts 組件中獲取產品 id 並將其傳遞給 ReadOne 組件,因為我無法在函數中獲取 id 並且無法顯示產品。 我怎樣才能做到這一點?
在 Product.js 中添加這個
我們設置id的初始狀態。
我們在 Product.js 中添加 setProductId ,因為這是 id 的狀態,以便您在 ReadOne.js 中使用它。
constructor(props) {
super(props);
this.state={
id:' ',
}
}
setProductId(id) => {
this.setState({ id:id })
}
然后將 id 作為道具傳遞給 ReadOne 組件。
<Route path='/products/:id' render={()=> <ReadOne id={this.state.id}/>}>
這是 id 的 getter,將其添加到 ReadProducts.js 中
showProduct = (id) => {
getProduct(id);
}
<Link to={`/products/${product.id}`}><button onClick={this.showProduct(product.id)}>{product.name}</button></Link>
現在您可以在 Product.js 中的任何組件中使用 id
當您使用組件(而不是渲染或子組件,如下所示)時,路由器使用 React.createElement 從給定組件創建一個新的 React 元素。 這意味着如果您為組件 prop 提供內聯函數,您將在每次渲染時創建一個新組件。 這會導致卸載現有組件並安裝新組件,而不僅僅是更新現有組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.