gpt4 book ai didi

javascript - react : How to pass an argument to a parent component

转载 作者:行者123 更新时间:2023-12-02 23:00:19 24 4
gpt4 key购买 nike

所以我有一个父组件,它充当我的应用程序中所有组件的路由器。

在我的子Login组件中,如果用户成功登录,它会生成一个 token ,并且我希望将此 token 传递给父组件,以便它可以将用户定向到仪表板,并将 token 传递给该Dashboard组件。

我的Login的登录处理部分:

//...
handleSubmit = event => {
event.preventDefault();

let username = this.state.username;
let password = this.state.password;

SignInAndGetToken(username, password)
.then(response => {
if (response.data["code"] === 200) {
let newToken = response.data["token"];
console.log("token = " + newToken);

console.log("submitting with username: " + username + " pwd: " + password);
this.props.newLogin(newToken, username)
}
})
.catch(function (error) {
console.log(error);
})
};
// ...

// SignInHandler.js
export const SignInAndGetToken = (username, password) =>
Axios.post(LoginPath, {
"username": username,
"password": password
});

父组件(App.js):

import React, {Component} from 'react';
import {Route, Switch} from "react-router";
import Home from "./components/Home";
import MyNavbar from "./components/MyNavbar";
import Register from "./components/auth/Register";
import Dashboard from "./components/dashboard/Dashboard";
import Login from "./components/auth/Login";

class App extends Component {
constructor(props) {
super(props);

this.state = {
token: "",
username: ""
}
}

newLogin(token, username) {
this.setState({
token: token,
username: username
})
}

render() {
return (
<React.Fragment>
<MyNavbar/>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/login" component={Login}/>
<Route exact path="/register" component={Register}/>

<Route path="/dashboard"
render={(props) =>
<Dashboard {...props}
token={this.state.token}
username={this.state.username}/>
}
/>
</Switch>
</React.Fragment>
);
}
}

export default App;

我已阅读 this example ,但它的父函数不带任何参数。

有没有办法从 Login 组件调用 newLogin(token, username) 方法?还是这个逻辑是错误的?

最佳答案

根据您的代码,您需要将 newLogin 函数传递给登录路由,如下代码所示,和因为我认为这不是正确的方法,所以你所做的您需要将该 token 存储在本地存储中,以便您将在整个系统中使用该 token

<Route path="/login" render={(props) => <Login {...props} newLogin= {(token, username) => this.newLogin(token, username)} /> } />

关于javascript - react : How to pass an argument to a parent component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57818112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com