如何在 React 中解构这个函数形式的 props?

问题描述 投票:0回答:2

如果这是一个愚蠢的问题,我深表歉意,但我正在学习 React 和 useState。我有下面的代码充当注册功能。当用户名和密码为

POST
API
时,会返回一条消息以及一个令牌。

import { useState } from "react";
const API_URL = '';

export default function SignUpForm() {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState(null);
    
    

    

    async function handleSubmit(event) {
        event.preventDefault();
        
        try {
            const response = await fetch(API_URL, {
                method: "POST",
                body: JSON.stringify({
                    username:username,
                    password:password,
                }),
                headers: {
                    'Content-type': 'application/json; charset=UTF-8'
                }
            })
            
            const result = await response.json();
            console.log(result);


            //Attempting to use state function to grab token and store it. 
            setToken(result.token);
            console.log(token)

            
        } catch (error) {
            setError(error.message)
        }
        
      }

    

    return (
    <>
        <h2>Sign Up!</h2>
        {error && <p>{error}</p>}
        <form onSubmit={handleSubmit}>
            <label>
                Username: <input value={username} onChange={(e) => setUsername(e.target.value)}/> 
            </label>
            <label>
                Password: <input value={password} onChange={(e) => setPassword(e.target.value)}/>
            </label>
            <button>Submit</button>
        </form>
    </> 
    );
  }

我正在尝试使用下面的

useState
文件中的
App.jsx
 const [token, setToken] = useState(null);
设置令牌。

import './App.css'
import SignUpForm from './components/SignUpForm'
import Authenticate from './components/Authenticate'
import { useState } from 'react';

function App() {
  const [token, setToken] = useState(null);

  return (
    <>
      
      <SignUpForm token={token} setToken={setToken} />

      <Authenticate token={token} setToken={setToken} />

    </>
  );
}

export default App

我被告知“从

setToken
解构
props
函数。”但我不知道这意味着什么。我不确定是否需要在当前文件中创建另一个相同类型的
useState
。我该如何解构
setToken
?有人可以帮我解决这个问题或为我指出正确的方向吗?非常感谢任何帮助!

如果有人问,

API_URL
确实有价值,我只是出于安全原因将其取出。

javascript reactjs react-hooks
2个回答
0
投票

您需要对 SignUpForm 组件进行一些更改:

 export default function SignUpForm(props){
          //deconstruct your props 
          const {token , setToken} = props
          //rest of your code 
 }

0
投票

这对你有用:

export default function SignUpForm({token, setToken}) {
  // your code 
}

在这里你可以看到详细的解释:

https://react.dev/learn/passing-props-to-a-component#step-2-read-props-inside-the-child-component

© www.soinside.com 2019 - 2024. All rights reserved.