我创建了一个用户组合反应应用程序。此应用程序具有身份验证,以便只有登录用户才能看到:注册用户+他们的投资组合。在我的App.js组件中,我存储了用户的道具。在我的Portfolio组件中,名为'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传递给组件。