[英]How to access the users details in different components
我創建了一個用戶組合反應應用程序。 此應用程序具有身份驗證,因此只有登錄用戶才能看到:注冊用戶 + 他們的投資組合。 在我的 App.js 組件中,我存儲了用戶的道具。 在名為“Folio”的我的投資組合組件中。 我可以使用以下變量this.props.match.params.id
訪問登錄用戶 ID,並顯示登錄用戶 ID。 我想知道如何以這種方式訪問用戶名或電子郵件。 經過多次嘗試,我似乎只能訪問用戶 ID
這是來自 App.js 的代碼
class App extends Component {
constructor() {
super();
this.state = {loggedIn: false, user: {email: '', name:''}};
this.logout = this.logout.bind(this);
this.login = this.login.bind(this);
}
logout(props) {
axios.get('api/logout')
.then(res => {
this.setState({loggedIn: false});
props.history.push('/');
})
.catch( err => console.log(err));
return null;
}
login(user) {
this.setState({loggedIn: true, user: user});
}
這是 Folio 組件。 請注意我如何使用this.props.match.params.id
訪問用戶 ID,但我無法訪問名稱或電子郵件。
export default class Folio extends Component {
constructor(props) {
super(props);
this.state = {
folio: []
};
}
componentDidMount() {
console.log('Howdy ' + `${this.props.match.params.id}`);
console.log('Howdy ' + `${this.props.user.name}`);
axios.get(`/api/users/${this.props.match.params.id}/folios`)
.then(response => {
this.setState({folio: response.data});
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
我只是在路由中添加:id
<Link to={`/folio/${this.props.id}`}>
<button className="button is-link" type="button">
View Portfolios
</button>
</Link>
<Route path="/folio/:id" render={(props) => <Folio {...props} user={this.state.user}/>} />
但是我也在尋找這個名字。
您應該像使用id
一樣將它們傳遞給組件,並且應該以相同的方式訪問它們,例如 => this.props.match.params.name
。 我猜您只是將 id 傳遞給組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.