我把子組件的 API 值拿到 axios 上,然后以toParentUser
. 在父組件中,該值是userInvalid
,并且可以在控制臺中很好地檢查。但是如果我想將值用作父組件中的變數,但我嘗試將其用作變數,則會出現錯誤userInvalid is not defined no-undef。如何在父組件中使用此值?如果你讓我知道,我將不勝感激謝謝
注冊用戶輸入:
這是子組件。我通過 axios 收到值并交給userData.data.isSuccess
父組件。
import React, { useEffect, useState } from 'react'
import styled from 'styled-components';
import axios from 'axios';
const InputWrap = styled.div`
align-items: center;
-webkit-appearance: none;
background: rgb(250, 250, 250);
border: 1px solid rgb(219, 219, 219);
border-radius: 3px;
box-sizing: border-box;
`
function SignUpUserInput({userName,setUserName,toParentUser}) {
//validation check
useEffect (()=> {
async function fetchData () {
try{
const userData = await axios({
method : 'get',
url : `https://cors-anywher.herokuapp.com/https://clone-instagram.shop:8080/users/checkid?id=${userName}`
});
toParentUser(userData.data.isSuccess)
}
catch(error) {
alert(error);
}
}
fetchData();
},[userName])
const [isUserName, setIsUserName] = useState(true);
const onCheckName = (e) => {
}
return (
<InputWrap isUserName={isUserName}>
<label className='inputLabel'>
<input className='inputInput' value={userName} onChange={(e)=>{setUserName(e.target.value); onCheckName(e);}}/>
</label>
</InputWrap>
)
}
export default SignUpUserInput;
注冊.jsx:
這是父組件。我得到了價值userInvalid
并想在這個組件中使用這個值
import React, { useState } from 'react'
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import SignUpLoginButton from '../components/SingUp/SignUpLoginButton';
import SignUpUserInput from '../components/SingUp/SignUpUserInput';
const SignUpWrap = styled.div`
flex-direction: column;
display: flex;
position: relative;
z-index: 0;
`
function SignUp() {
const toParentUser = (userInvalid) => {
console.log('??', userInvalid)
}
// I want to use this value
const useThis = userInvalid;
const [userName, setUserName] = useState("");
return (
<SignUpWrap>
<div className='signUpInputContent4'>
<SignUpUserInput userName={userName} setUserName={setUserName} toParentUser={toParentUser}/>
</div>
<div className='signUpInputContent6'>
{/* want to use value here */}
<Link to='/birthday' style={{textDecoration : 'none' ,color: 'inherit', pointerEvents: userInvalid && 'none'}}>
<div className='signUpInputLoginButton'>
<SignUpLoginButton email={email} name={name} userName={userName} passWord={passWord}/>
</div>
</Link>
</div>
</SignUpWrap>
)
}
export default SignUp;
uj5u.com熱心網友回復:
您不能將 userInvalid 存盤在 useThis 中,因為 userInvalid 超出范圍,因此將未定義,因此請執行以下操作:
const [useThis,SetuseThis]=useState('');
const toParentUser = (userInvalid) => {
console.log('??', userInvalid)
SetuseThis(userInvalid)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526335.html
標籤:反应
上一篇:如何根據背景更改按鈕顏色?