如何访问不同组件中的用户详细信息

问题描述 投票:-1回答:1

我创建了一个用户组合反应应用程序。此应用程序具有身份验证,以便只有登录用户才能看到:注册用户+他们的投资组合。在我的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}/>} />

不过我也在寻找这个名字。

javascript reactjs authentication react-router one-to-many
1个回答
0
投票

你应该像使用id一样将它们传递给组件,你应该以相同的方式访问它们,例如:> this.props.match.params.name。我猜你只是将id传递给组件。

© www.soinside.com 2019 - 2024. All rights reserved.