[英]How to pass hook function to react functional component
I have been unsuccessful at passing a State Hook to a child functional component in React Js.我未能将 State Hook 传递给 React Js 中的子功能组件。 The passed function prints undefined and the console says "error signing in TypeError: updateUser is not a function".
传递的 function 打印未定义,控制台显示“错误登录 TypeError:updateUser 不是函数”。 The parent component is the App.js component and the child component is LoginPage.js.
父组件是 App.js 组件,子组件是 LoginPage.js。 My end goal is ensure the user is authenticated throughout the app using AWS Cognito/AWS Amplify.
我的最终目标是确保使用 AWS Cognito/AWS Amplify 在整个应用程序中对用户进行身份验证。 If the user state is not authenticated, I send the user to the LoginPage.
如果用户 state 未通过身份验证,我将用户发送到 LoginPage。
Specifically, as seen below, i pass "updateUser={updateUser}" to the LoginPage.js component, it is read as "LoginPage({updateUser})", and used as "updateUser(user)".具体来说,如下所示,我将“updateUser={updateUser}”传递给 LoginPage.js 组件,它被读取为“LoginPage({updateUser})”,并用作“updateUser(user)”。 The simplified parent and child components are as followed:
简化的父子组件如下:
function App() {
const [user, updateUser] = useState(null);
useEffect(() => {
checkUser()
}, []
)
async function checkUser() {
try {
const user = await Auth.currentAuthenticatedUser();
updateUser(user)
}
catch (e) {
console.log(e)
}
}
if (!user) {
return <LoginPage updateUser={updateUser} />
} else {
return (
<div>
<BrowserRouter>
<Switch>
<Route path="/" component={LoginPage} exact />
<Route path="/HomePage" component={HomePage} exact />
</Switch>
</BrowserRouter>
</div>
);
}
}
export default App;
export default function LoginPage({updateUser}) {
async function signIn(e) {
e.preventDefault()
const {email, password} = formState
try {
await Auth.signIn(email, password);
const user = await Auth.currentAuthenticatedUser();
console.log(updateUser) // updateUser is undefined
updateUser(user)
})
} catch (error) {
console.log(error)
}
}
return (
<div>
// Login page here, but irrelevant
<div>
)
}
LoginPage.propTypes = {
updateUser: PropTypes.func.isRequired
}
I think the problem is that in both cases, that is when user is authenticated as well as when user is not authenticated, you are rendering the LoginPage
.我认为问题在于,在这两种情况下,即当用户通过身份验证以及用户未通过身份验证时,您都在呈现
LoginPage
。
So you have to either update your logic to show LoginPage
component only when the user is not logged in or if you want to keep same logic, then in the else
condition in App
component, you have to pass in a render prop function called updateUser
, such that it doesn't lead to error, like so:因此,您必须更新您的逻辑以仅在用户未登录时显示
LoginPage
组件,或者如果您想保持相同的逻辑,那么在App
组件的else
条件下,您必须传入一个名为updateUser
的渲染道具 function ,这样就不会导致错误,如下所示:
<Route exact path="/" render={(props) => <LoginPage updateUser={(args) => console.log("Your update function")} {...props} />} />
I recommend modifying your logic and going with my former suggestion.我建议修改您的逻辑并按照我以前的建议进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.