![](/img/trans.png)
[英]React: How to pass State value to another component and use it to render a component
[英]How do i pass the properties of an object whose state is set in one component through a link and render them in another component in React
我有兩個組件和一條路線。 我想傳遞 place 對象的屬性,以便我可以在其他組件中呈現它們。 我有一個組件,它的位置設置為 state。 在那個組件中,我為每個單獨的地方繪制了鏈接。 當我單擊鏈接時,我希望能夠訪問包含有關該地點信息的單個頁面。 出於某種原因,我根本無法訪問該對象。 有任何想法嗎 ?
import React, { useState, useEffect } from "react";
import axios from "axios";
import PlaceVisited from "./PlaceVisited";
import {
Link,
BrowserRouter as Router,
Route,
Redirect
} from "react-router-dom";
const UserPersonal = () => {
const [user, setUser] = useState([1]);
const [place, setPlace] = useState([
{ id: 6, placeVisited: "Kuaa Lumpur", country: "Malaysia", user_id: 1 },
{ id: 7, placeVisited: "Bangkok", country: "Thailand", user_id: 1 }
]);
return (
<div>
{place.map(place => (
<Places key={place.id} place={place} />
))}
</div>
);
};
const Places = ({ place }) => {
return (
<div>
City:
<Link
to={{
pathname: `/places/${place.id}`,
data: { place }
}}
>
{place.placeVisited}
</Link>
</div>
);
};
export default UserPersonal;
組件 2
import React, {useState, useEffect} from "react";
const PlaceVisited = (props) => {
`const [places, setPlaces] = useState('')`
useEffect(()=>{
setPlaces(props.place.placeVisited)
},[])
}
return (
<div>
<p>placevisited</p>
<h2>{places}</h2>
</div>
);
export default PlaceVisited
路由器
<Router>
<Route path="/places/:id" component={PlaceVisited} />
</Router>
如何使用 React Router 將數據傳遞給組件有兩種選擇。
請參閱有關如何解決此問題的博客文章: https : //tylermcginnis.com/react-router-pass-props-to-link/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.