简体   繁体   中英

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.

but I can't import the id because it's inside a function, so I can't get it

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.

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

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.

By using the useParams hook from react-router-dom ;

Link to an example - 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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