簡體   English   中英

使用反應從頁面導入數據

[英]Import Data from a page with react

我有一個 web 應用程序在反應,我有兩個注冊頁面,一個用戶和下一個注冊項目的地方,我需要獲取在上一頁注冊的用戶 ID 才能在下一頁注冊項目。

但我無法導入 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}`);
    }

我正在嘗試像這樣導入

import { _idUser } from './Register';

他返回給我這個錯誤:打印

路線: 路線

我認為您正在使用react-routerreact-router-dom進行導航。

對於這兩個庫,您都可以將一些數據作為道具傳遞給下一個組件,例如在您的情況下 -

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

在您的下一個組件中,您可以通過

props.location.state

但最好的方法是從參數中獲取它,因為您的 url 中有該 ID。

通過使用react-router-dom中的useParams鈎子;

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM