简体   繁体   English

使用反应从页面导入数据

[英]Import Data from a page with react

I have a web application in react, and I have two registration page, one user and the next where you register a project, I need to get the user id that was registered on the previous page to register the project on the next page.我有一个 web 应用程序在反应,我有两个注册页面,一个用户和下一个注册项目的地方,我需要获取在上一页注册的用户 ID 才能在下一页注册项目。

but I can't import the id because it's inside a function, so I can't get it但我无法导入 id,因为它在 function 中,所以我无法获取

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}`);
    }

I'm trying to import like this我正在尝试像这样导入

import { _idUser } from './Register';

And he returns me this error:他返回给我这个错误:打印

Routes:路线: 路线

I am taking that you are using react-router or react-router-dom for navigation.我认为您正在使用react-routerreact-router-dom进行导航。

For both the libraries you can pass some data as props for the next component like this in your case -对于这两个库,您都可以将一些数据作为道具传递给下一个组件,例如在您的情况下 -

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

and in your next component you can access it by在您的下一个组件中,您可以通过

props.location.state

But the best way is to get it from params since you have that id in your url.但最好的方法是从参数中获取它,因为您的 url 中有该 ID。

By using the useParams hook from react-router-dom ;通过使用react-router-dom中的useParams钩子;

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

Quick suggestion: since you are pushing idUser in history.push('/freela/${_idUser} , you can probably extract _idUser from the URL快速建议:由于您在history.push('/freela/${_idUser}中推送idUser ,您可能可以从 URL 中提取_idUser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM