简体   繁体   English

如何通过钩子 function 反应功能组件

[英]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.

相关问题 如何在React的功能组件中将参数传递给功能 - How to pass arguments to function in functional component in React 如何将此 React 钩子组件转换为功能组件 - How to convert this React hook component into a functional component 如何在功能组件中调用 react hook fetch 请求来访问数据然后传递给类组件进行映射? - How to call a react hook fetch request in a functional component to access data then pass to a class component to map? 使用useState挂钩对功能组件进行反应,立即执行功能 - React functional component with useState hook executes function immediately 如何在反应中将类组件作为功能道具传递? - How to pass class component as a functional prop in react? 如何在 React 功能组件中的 onClick 上传递参数 - How to pass parameter on onClick in React Functional Component 如何在反应功能组件或钩子中有效地初始化客户端注册回调 - How to effectively initialise client register callback in react functional component or hook 如何在反应功能组件中正确使用 useRef 挂钩? - How to use useRef hook properly in react Functional Component? 如何在 React js 中的功能组件外部使用 useHistory() 挂钩? - How to use useHistory() hook outside functional component in React js? 如何将 React Hook 传递给子组件 - How to pass a React Hook to a child component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM