gpt4 book ai didi

reactjs - 将用户名从登录组件传递到主页组件

转载 作者:行者123 更新时间:2023-12-03 14:26:59 25 4
gpt4 key购买 nike

如果我有一个像这样的登录页面组件...

class Login extends Component {
constructor(props) {

super(props);
this.state = {
username: ""
};

并且我想在主页上访问该用户名,以通过获取显示用户特定的信息,我该怎么做?

class AccountItem extends Component {

constructor(props) {
super(props);
this.state = {
username : // How to get the same field as Login username here?
};
}

最佳答案

处理此问题的最佳方法是使用 React.createContext(如果您有 React 16.3),在应用程序级别更新状态,或者有一个状态管理系统,例如Redux 来跟踪您当前的用户名。

Example with React.createContext which I highly recommend using if you don't have a state management

// This is where you have your routes etc.
import * as React from 'react';

const UsernameContext = React.createContext('');

class App extends Component {

constructor(props) {
super(props);
this.state = { username: '' };
}

onUsernameChange = (username) => {
this.setState({
username: username
});
}

render() {
<UsernameContext.Provider value={this.state.username}>
<Switch>
<Route exact path="/" render={Home} />
<Route path="/login" render={()=><LoginPage onUsernameChange={this.onUsernameChange}/>
</Switch>
</UsernameContext.Provider>
}
}


class Login extends Component {
constructor(props) {

super(props);
this.state = {
username: ""
};
}

onSubmit = () => {
// This is pseudo code so you want to handle login somewhere
// when that is done you can call your onUsernameChange
this.props.onUsernameChange(this.state.username);
};

...
}


class AccountItem extends Component {

render() {
return (
<UsernameContext.Consumer>
{(username) => {
// you have username in props
}}
</UsernameContext.Consumer>
)
}

下面是一个没有 ReduxReact.createContext 的简单示例

// This is where you have your routes etc.
class App extends Component {

constructor(props) {
super(props);
this.state = { username: '' };
}

onUsernameChange = (username) => {
this.setState({
username: username
});
}

render() {
<Switch>
<Route path="/login" render={()=><LoginPage onUsernameChange={this.onUsernameChange}/>
<Route path="/account" render={() => <AccountItem username={this.state.username} />} />
</Switch>
}
}


class Login extends Component {
constructor(props) {

super(props);
this.state = {
username: ""
};
}

onSubmit = () => {
// This is pseudo code so you want to handle login somewhere
// when that is done you can call your onUsernameChange
this.props.onUsernameChange(this.state.username);
};

...
}


class AccountItem extends Component {

render() {
this.props.username // you have username in props

关于reactjs - 将用户名从登录组件传递到主页组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49783155/

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