【问题标题】:Import Data from a page with react使用反应从页面导入数据
【发布时间】:2020-03-12 15:20:50
【问题描述】:

我有一个 web 应用程序在 react 中,我有两个注册页面,一个用户和下一个您注册项目的页面,我需要获取在上一个页面上注册的用户 id 以便在下一个页面上注册项目页面。

但我无法导入 id,因为它在函数内部,所以我无法获取它

export default function Register({ history }) {
    const [username, setUsername] = useState('');
    const [email, setEmail] = useState('');
    const [passwd, setPasswd] = useState('');

    async function handleSubmit(e) {
        e.preventDefault();

        const response = await api.post('/createUser',  {
            username, email, passwd,
        });

        console.log(response.data);
        const { _id: _idUser } = response.data;

        history.push(`/freela/${_idUser}`);
    }

我正在尝试像这样导入

import { _idUser } from './Register';

他返回给我这个错误:

路线:

【问题讨论】:

    标签: javascript html reactjs web


    【解决方案1】:

    我认为您正在使用 react-routerreact-router-dom 进行导航。

    对于这两个库,您可以将一些数据作为道具传递给下一个组件,例如在您的情况下 -

    history.push(/freela/${_idUser}, _idUser);

    在您的下一个组件中,您可以通过

    访问它

    props.location.state

    但最好的方法是从参数中获取它,因为你的 url 中有那个 id。

    通过使用来自react-router-domuseParams 钩子;

    示例链接 - https://reacttraining.com/react-router/web/example/url-params

    【讨论】:

    • 我用了getParams,但它返回一个空变量,我也试过你说的关于props的方法,但它也告诉我没有设置props,我需要导入一些东西吗?关于useParams,我这样说: const { _idUser } = useParams();
    • @LuísGustavo 你能告诉我你是如何为这个特定的路线设置路线的吗?
    • 在帖子中添加了打印件
    • 我设法get or id,但是耍了个花招,在/中使用split分隔,并且id总是在位置4,我认为这不是最好的格式,但它是唯一的一个有效的,可以帮助我做正确的方法,感激!
    • @LuísGustavo 你可以通过{ id } = useParams();获取你的ID
    【解决方案2】:

    快速建议:由于您在history.push('/freela/${_idUser} 中推送idUser,您可能可以从URL 中提取_idUser

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      相关资源
      最近更新 更多