【问题标题】:React Js pass boolean back to parent stateReact Js 将布尔值传递回父状态
【发布时间】:2017-12-11 13:43:25
【问题描述】:

我在导航栏组件上有登录名,但我的主要组件上有一些东西需要在有人登录时更新,我可以让导航栏上的登录名正常工作,但变量没有被传递回调用导航栏的父代码如下所示

<LoginBar AuthRes={this.state.AuthResults} IsLoggedIn={this.state.isLoggedIn}/>

这是将变量 IsLoggedIn 传递到我的导航栏中,然后在我的导航栏中我的代码是这样的

LoginAuth = (Res) => {
    if (Res.username === this.state.Username && Res.password === this.state.Password) {
        this.setState({
            IsLoggedIn: true,
        }, function(){

        });
        this.hideModal();

    } else {
        console.log("Gets to login auth and false");
    }
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.map(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        self.LoginAuth(Res);
    });
}

所以点击登录时,它会询问您的详细信息,然后它将使用 .map 浏览我拥有的文件中的所有登录详细信息,然后将其传递给 LoginAuth,它将检查输入是否与身份验证文件匹配,并且将 IsLoggedIn 设置为 true 如果它匹配我将如何将 IsLoggedIn 推回父级以更改那里的内容

一旦我找到正确的循环,我将如何打破循环,就好像我有一个警告说 alert("Incorrect username or password") 如果所有三个值都没有得到满足,则这样做 3 次

谢谢安迪

编辑:

当我执行 this.props.IsLoggedIn(true) 或 this.props.isLoggedIn(true) 时,我收到错误 TypeError: Cannot read property 'props' of undefined 所以它说 isLoggedIn 和 IsLoggedIn 尚未定义

state = { AuthRes: this.props.AuthRes, isOpen: false, Username: '', Password: '', searchResults: [], testMode: true, isLoggedIn: this.props.IsLoggedIn, Auth: '', }

【问题讨论】:

    标签: javascript css reactjs jsx


    【解决方案1】:

    你可以做的是使用 props 将一个函数从 Parent 组件传递给 Child 组件。 假设您的父组件中有此功能:

    function doSomething(argument){
        console.log(argument);
    }
    

    现在将此函数传递给您的子组件:

    <LoginBar AuthRes={this.state.AuthResults} IsLoggedIn={this.state.isLoggedIn} doSomething={this.doSomething}/>
    

    然后,在子组件中,当您获得该功能时,只需从您需要的任何地方调用它:

    //Some code ...
    this.props.doSomething(argument)
    //Some code ...
    

    对于中断问题,您不能中断map 函数。您可以做的是将map 函数转换为for 循环并使用break 或在地图中使用一些标志来知道何时停止执行地图。看看这个https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break

    【讨论】:

    • 我需要将变量 IsLoggedIn 从子级传递回父级以更改其他不从父级传递给子级的东西我知道该怎么做
    • @andywilson 如果您仔细阅读评论,您会看到您正在将函数从父级传递给子级,但是您正在从子级调用函数,并且在该调用中您将变量 isLoggedIn 传递给父母。由于该函数属于parrent,它是在parent的上下文中执行的,所以当您调用传递给它的isLoggedIn参数的函数时,您将按字面意思将参数传递给parent。
    • 我更改了我的问题,以便它显示我得到的错误
    猜你喜欢
    • 2019-05-07
    • 2019-03-08
    • 2020-04-25
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多