首页 > 解决方案 > React JS 如何在 Hook 中的页面之间传递数据(useEffect)

问题描述

我试图将一个数据对象传递到另一页,但我无法获取第二页上的数据。下面的代码是我正在使用

第一页传递 LINK 中的数据

 <Link to={{ pathname: `${path}/users/${organization.id}`,
                                            data: organization
                                        }}>  <img src={config.s3Bucket + "/" + organization.logo} />
 </Link >

在这里,我在“数据”参数中传递对象

第二页

import React, { useState, useEffect } from 'react';
function UserList({ history, match }) {
const { path } = match;
const { id } = match.params;
const [organization, setOrganization] = useState(null);

// const { data } = this.props.location

useEffect(() => {
    
    // console.log(location.data);

}, []);  }   export { UserList };

我已经尝试了“location.data”和“this.props.location”,但我无法获取数据,请帮我解决这个问题。

标签: reactjsreact-hooks

解决方案


你可以这样做

<Link to={{ pathname: `${path}/users/${organization.id}`, state: organization}}>
   <img src={config.s3Bucket + "/" + organization.logo} />
 </Link >

并在第二页

import React, { useState, useEffect } from 'react';
import {useLocation} from 'react-router-dom';

function UserList({ history, match }) {
  const { path } = match;
  const { id } = match.params;
  const [organization, setOrganization] = useState(null);

  const { state } = useLocation();

  useEffect(() => {
    console.log(state);
  }, []);
}   

export { UserList };

推荐阅读