将数据作为道具传递时未定义

时间:2018-06-18 15:01:40

标签: javascript reactjs

我在undefineduser.login获得user.bio,无法通过 来自App.js的UserInfo组件的数据因为我没有通过任何国家 它只是道具。

App.js

render() {
                return (
                  <div>
                    <nav className="uk-navbar-container uk-margin" uk-navbar="true">
                      <div className="uk-navbar-left">

                        <a className="uk-navbar-item uk-logo" href="/">  Github search  &nbsp;
                          <span uk-icon="icon: github; ratio: 2.2" className="uk-margin-large-right"></span>
                        </a>
                        <div className="uk-navbar-item  uk-navbar-right">

                          <form onSubmit={this.submitUser}>
                            <input className="uk-input uk-form-width-medium"
                              type="text" placeholder="Github UserName...."
                              id="username" onKeyUp={this.onChange} ref="username"></input>
                            &nbsp;&nbsp;
                            <button className="uk-button uk-button-primary">Search &nbsp;
                            <span uk-icon="search" className="uk-margin-small-right"></span>
                            </button>
                          </form>

                        </div>
                        <div className="uk-navbar-item  uk-navbar-right"></div>
                      </div>
                    </nav>
                    <div className="uk-container-large">
                      <UserInfo name={this.props.username} />
                    </div>
                  </div>
                );
              }

UserInfo.js

import React, { Component } from 'react';

class UserInfo extends Component {
    constructor(props) {
        super(props)
        this.state = { userList: [] }
    }

    componentDidMount() {
        console.log('in child =' + this.props.name)
        fetch('https://api.github.com/users/${this.props.name}')
            .then(res => res.json())
            .then(userList => {
                this.setState({ userList: userList })
                console.log('data is :' + userList);
            });
    }

    render() {
        if (!this.state.userList) {
            return (<div className="uk-child-width-1-3@s uk-grid-match">Loading...</div>)
        }
        const user = this.state.userList;

        return (
            <div className="uk-child-width-1-3@s uk-grid-match" uk-grid="true">

                <h3> {user.login} </h3>
                <h3>{user.bio}</h3>
            </div>
        );
    }
}

export default UserInfo;

1 个答案:

答案 0 :(得分:1)

当你调用fetch库时字符串连接是错误的,你可以使用反引号而不是正常的顶点

fetch(`https://api.github.com/users/${this.props.name}`)

或使用普通的旧连接

fetch('https://api.github.com/users/' + this.props.name)

否则this.props.name不会被解释为实际变量,最终会得到404

enter image description here