【问题标题】:Unhandled Rejection (TypeError) on callback passed to react component回调传递给反应组件的未处理拒绝(TypeError)
【发布时间】:2022-01-26 04:52:22
【问题描述】:

我遇到了将回调函数传递给组件的问题。 这是我的 App.js 文件的一小部分

loginCompleted = (status) => {
        if (status == "1") {
            this.setState({ currentUser: "xxxx" });
        }
    }

    render() {
        return (
            <BrowserRouter>
                <MainTemplate authStatus={ this.state.currentUser }>
                    <Switch>
                        <Route exact path='/' component={Home} />
                        <Route exact path='/login' component={Login} loginCompleted={this.loginCompleted}  />
                    </Switch>
                </MainTemplate>
            </BrowserRouter>
        );
    }

如您所见,我想将 loginCompleted 回调传递给 Login 组件。

在登录组件中有处理提交表单的函数

handleSubmit = 异步 e => { e.preventDefault(); const token = await this.LoginService.loginUser(this.state.username, this.state.password); 如果(令牌){ 控制台.log(令牌); this.props.loginCompleted(token); this.props.history.push("/home"); } 别的 { console.log("NULL"); } }

我收到了错误

Unhandled Rejection (TypeError): this.props.loginCompleted is not a function

尽管进行了研究,但我仍然不明白为什么。你能帮助我吗? 谢谢!

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    似乎,您将 prop 传递给路由,而不是组件本身。试试这个方法。

    loginCompleted = (status) => {
            if (status == "1") {
                this.setState({ currentUser: "xxxx" });
            }
        }
    
        render() {
            return (
                <BrowserRouter>
                    <MainTemplate authStatus={ this.state.currentUser }>
                        <Switch>
                            <Route exact path='/' component={Home} />
                            <Route exact path='/login'> 
                              <Login loginCompleted={this.loginCompleted}  />
                           </Route>
                        </Switch>
                    </MainTemplate>
                </BrowserRouter>
            );
        }
    

    我们将 Component 包裹在 Route 中,并将 prop 传递给组件,而不是传递给 route。

    【讨论】:

    • 不!多么愚蠢的错误:-(非常感谢!
    • 太累的时候会发生))不客气!
    • 感谢您的理解!
    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2023-04-06
    • 1970-01-01
    • 2021-07-01
    相关资源
    最近更新 更多