React-router - React에서 페이지 간에 데이터를 전달하려면 어떻게 해야 합니까?
저는 한 페이지에서 다른 페이지로 데이터를 전달해야 하는 프로젝트를 진행하고 있습니다.예를 들어, 저는data
제1페이지에.
let data = [
{id:1, name:'Ford', color:'Red'},
{id:2, name:'Hyundai', color:'Blue'}
]
이 데이터 목록을 이름으로 렌더링하는 첫 번째 구성 요소 페이지입니다.
class ListDetail extends Component {
constructor();
handleClick(data){
console.log(data);
}
render() {
return (
<div>
<Hello name={this.state.name} />
<ul>
{data.map((data,i) => {
return <li onClick={this.handleClick.bind(this,data)}>{data.name}</li>
})}
</ul>
</div>
);
}
}
저는 이 데이터를 다음 페이지에 전달하고 싶습니다.이 페이지에는 이 데이터와 이 이상의 데이터가 필요합니다.리액트 라우터 4를 사용하고 있습니다.어떤 제안이나 도움도 도움이 될 것입니다.
리액트 라우터에서 Link 컴포넌트를 사용하여to={}
pathname을 루트로 지정하는 오브젝트로 지정합니다.그런 다음 변수를 추가합니다. data
전달하고 싶은 가치를 유지할 수 있습니다.아래 예를 참조하십시오.
사용방법<Link />
컴포넌트:
<Link
to={{
pathname: "/page",
state: data // your data array of objects
}}
>
사용.history.push()
this.props.history.push({
pathname: '/page',
state: data // your data array of objects
})
위의 옵션 중 하나를 사용하여data
페이지 컴포넌트의 아래 설명에 따라 Location 객체에 추가합니다.
render() {
const { state } = this.props.location
return (
// render logic here
)
}
다른 예에서는 값을 루트와 함께 전달하는 예를 볼 수 있습니다.
데이터를 대상 컴포넌트에 전달하는 가장 좋은 방법은 코드를 복사하여 붙여넣고 마법을 보는 것입니다.또한 상세하게 설명했습니다.
주의: react-router-dom v6에서는 후크를 대신 사용할 수 있습니다.
버전 5x
첫 번째와 두 번째 구성 요소가 있다고 가정합니다.첫 번째 컴포넌트에는 두 번째 컴포넌트를 대상으로 하는 링크가 있습니다.
링크가 있는 첫 번째 컴포넌트는 링크를 클릭하면 다음과 같이 타겟 패스로 이동합니다."/details"
.
import React from 'react';
import {Link} from 'react-router-dom';
export default function firstComponent() {
return(
<>
<Link to={{
pathname: '/details',
state: {id: 1, name: 'sabaoon', shirt: 'green'}
}} >Learn More</Link>
</>
)
}
이제 두 번째 구성 요소에서 전달된 개체에 다음과 같이 액세스할 수 있습니다.
import React from 'react'
export default class Detials extends React.Component{
constructor(props){
super(props);
this.state={
value:this.props.location.state,
}
}
alertMessage(){
console.log(this.props.location.state.id);
}
render(){
return (
<>
{/* the below is the id we are accessing */}
hay! I am detail no {this.props.location.state.id} and my name is
{this.props.location.state.name}
<br/>
<br/>
{/* press me to see the log in your browser console */}
<button onClick={()=>{this.alertMessage()}}>click me to see log</button>
</>
)
}
}
주의: react-router-dom 버전6에서는 위의 메서드는 클래스 컴포넌트에서는 동작하지 않습니다.단, useLocation 훅을 사용하여 react의 기능 컴포넌트를 사용할 수 있습니다.그 후 다른 컴포넌트의 해당 위치를 통해 상태 객체를 그릴 수 있습니다.
버전 6
react-router-dom의 훅 v6을 사용하여 동일한 것을 달성하는 방법
기능적인 컴포넌트가 2개 있다고 합시다.첫 번째 컴포넌트 A와 두 번째 컴포넌트 B입니다.구성 요소 A는 구성 요소 B와 데이터를 공유하려고 합니다.
후크 사용방법: (use Location, use Navigate)
import {Link, useNavigate} from 'react-router-dom';
function ComponentA(props) {
const navigate = useNavigate();
const toComponentB=()=>{
navigate('/componentB',{state:{id:1,name:'sabaoon'}});
}
return (
<>
<div> <a onClick={()=>{toComponentB()}}>Component B<a/></div>
</>
);
}
export default ComponentA;
이제 컴포넌트 B의 데이터를 가져옵니다.
import {useLocation} from 'react-router-dom';
function ComponentB() {
const location = useLocation();
return (
<>
<div>{location.state.name}</div>
</>
)
}
export default ComponentB;
리액트 라우터의Link
컴포넌트 및 다음 작업을 수행합니다.
<Link to={{
pathname: '/yourPage',
state: [{id: 1, name: 'Ford', color: 'red'}]
}}> Your Page </Link>
그 후, 데이터 액세스에 대해this.props.location.state
애플리케이션 전체의 스테이트 관리에 redux 를 사용하는 것도 고려할 수 있습니다(https://redux.js.org/)).
reactjs의 다른 컴포넌트 라우터에 데이터를 전달하는 방법
Login.jsx
handleClickSignIn(){
console.log("come handle click fun");
this.props.history.push( {pathname: "/welcome",
state: { employee:"Steven" }});
}
환영해.jsx
componentDidMount()
{
console.log(this.props.location.state.employee);
}
react-router-dom 6.4.3을 사용하고 있습니다.
다음은 다른 이전 버전이나 이전 버전에서는 동작하는 것처럼 보이지만 6.4.3에서는 동작하지 않습니다.
import { Link } from "react-router-dom";
<Link
to={{
pathname: '/details',
state: stateObj
}}>Learn More</Link>
약간의 변경이 이루어졌으며 대신 다음과 같은 작업이 수행됩니다.
<Link
to={'/details'}
state={stateObj}>Learn More</Link>
스테이트 오브젝트가 to 오브젝트 밖에 있는 것을 알 수 있습니까?
[ Details ]페이지에서 다음과 같이 오브젝트를 수신할 수 있습니다.
import { useLocation } from "react-router-dom";
const DetailsPage: FC<{}> = (props) => {
const { state } = useLocation();
//do stuff with state obj
}
데이터를 네비게이트 하는 것은 매우 간단합니다.(다른 컴포넌트에)
import { useNavigate } from "react-router-dom";
const navigate=useNavigate()
"네비게이션으로 value.id을 통과해야 합니다.이것을 사용해 보세요."
onClick={() => {history( /userUpdate,{ state: { id: value.id } })}}
""그럼 "userUpdate" 컴포넌트 =>"에 있습니다."
import {useLocation} from 'react-router-dom'
const { state } = useLocation(); const { id } = state;
console.log(id)
value.id 입니다.
다른 페이지가 컴포넌트라고 가정하면 다음 페이지에서 사용할 수 있도록 데이터를 소품으로 전달할 수 있습니다. 주의할 점은 꼭 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아,<Link />
에서 할 수 있는 react-router 4
하는 것과는 달리<a></a>
그러면 페이지 전체가 새로고침되므로 손실된 데이터에 액세스할 수 있습니다.
아래 코드와 같은 하나의 오브젝트로1 페이지를 송신하는 경우는, 오브젝트 파일의 페이지를 Import 하고, 행선지 파일의 페이지를 재차 Import 할 필요가 있습니다.
import Home from './componenets/home/home';
import ColdDrink from './componenets/coldDrink/coldDrink';
import HotDrink from './componenets/hotDrink/hotDrink';
import CheaseCake from './componenets/cheaseCake/cheaseCake';
import Lost from './componenets/404/lost';
const link = [
{
name : "Cold Drink",
link : "/ColdDrink",
router : <ColdDrink/>
},
{
name : "Hot Drink",
link : "/HotDrink",
router : <HotDrink/>
},
{
name : "chease Cake",
link : "/CheaseCake",
router : <CheaseCake/>
},
{
name : "Home",
link : "/",
router : <Home/>
},
{
name : "",
link : "",
router : <Lost/>
}
];
대상 파일에서 객체를 매핑해야 합니다.
const links = (this.props.link);
{links.map((item, i) => (
{item.router}
))}
데이터,는 상 the, 재 the에 .Checkout.tsx
및 를 pass합니다.App.tsx
사용)
Checkout.tsx 페이지
import { useHistory } from 'react-router-dom';
export default function CheckoutPage() {
const history = useHistory();
const data = [
{
name: "Ngoc",
id: 1
},
{
name: "Kevin",
id: 2
},
{
name: "Jack",
id: 3
},
];
history.push({
pathname: `/app`, /* this path field is based on your project */
state: data ? data : [] /* pass state data to app page */,
});
}
App.tsx 페이지
import { useLocation } from 'react-router-dom';
export default function AppPage() {
const history = useHistory();
// use useLocation read data form Checkout page
const location = useLocation<any>();
const currentDataFromCheckoutPage = location.state;
// data pass show here
console.log('currentDataFromCheckoutPage', currentDataFromCheckoutPage);
}
언급URL : https://stackoverflow.com/questions/52238637/react-router-how-to-pass-data-between-pages-in-react
'source' 카테고리의 다른 글
모듈을 찾을 수 없습니다.'@date-io/date-fns'을(를) 확인할 수 없습니다. (0) | 2023.02.23 |
---|---|
C# JSON의 자동 속성 역직렬화 (0) | 2023.02.23 |
MongoDB 문서 및 컬렉션 시각 관리 (0) | 2023.02.23 |
스프링 부트를 사용한 Maven 리소스 필터링: 자리 표시자를 확인할 수 없습니다. (0) | 2023.02.23 |
"매직 따옴표"가 비활성화되어 있는데, 왜 PHP/WordPress는 계속해서 내 POST 데이터를 자동 이스케이프합니까? (0) | 2023.02.23 |