在React.js中向服务器发出GET请求

时间:2017-05-19 08:25:07

标签: javascript reactjs get

我有SearchBarProfile组件,我想向服务器发出GET请求:http://awesomeserver/users。服务器中的数据位于对象数组中。我希望能够在搜索栏中输入用户名,当我点击“搜索”时,我想在页面上显示该用户的名字,姓氏和电子邮件。例如,当我搜索jsmith时,我想显示:名字:John,姓氏:Smith,电子邮件:jsmith@gmail.com。为此,我需要将它们作为props传递给Profile组件。我正在使用axios来发出请求,但我认为我没有正确使用它。如何按用户名搜索,但只检索名字,姓氏和电子邮件?

这是示例数据在服务器中的样子:

{
  username: jsmith,
  firstName: John,
  lastName: Smith,
  email: jsmith@gmail.com,
  hobby: hiking,
  id: 1
}

到目前为止,这是我的代码:

//Profile Component

import React, { Component } from 'react';


class Profile extends Component {
  render() {
    return (
        <div>
            <div>First Name: {this.props.firstName}</div>
            <div>Last Name: {this.props.lastName}</div>
            <div>Email: {this.props.email}</div>
        </div>
    );
  }
}

export default Profile;



//SearchBar component

import React, { Component } from 'react';
import axios from 'axios';

import Profile from './Profile';

class SearchBar extends Component {

  constructor(props) {
  super(props);
  this.state = {
    fetchUser: {
      username: '',
      firstName: '',
      lastName: '',
      email: '',
      hobby: ''
    }
  }
  this.fetchUser = this.fetchUser.bind(this);
}


 fetchUser() {
    var id = this.refs.id.value;

    axios.get('http://awesomeserver/users/${id}')
      .then(resp => resp.json()) 
      .then( (response) => {
        console.log(response);
        this.setState({
          fetchUser: response.data
        });
      })
      .catch( (error) => {
        console.log(error);
      });  
  }

  render() {
    return (
      <div>
          <input ref="id" placeholder="Enter in a username" />
          <button onClick={this.fetchUser}>Search</button>
          <Profile firstName={this.fetchUser.firstName} lastName={this.fetchUser.lastName} email={this.fetchUser.email} />
      </div>
    );
  }
}

export default SearchBar;

3 个答案:

答案 0 :(得分:3)

这里使用axios的方式不正确,我们需要将返回值正确设置为props,我们还需要正确绑定axios回调函数,例如,您的代码应如下所示:

import React, { Component } from 'react';


class Profile extends Component {
  render() {
    return (
        <div>
            <div>First Name: {this.props.firstName}</div>
            <div>Last Name: {this.props.lastName}</div>
            <div>Email: {this.props.email}</div>
        </div>
    );
  }
}

export default Profile;



//SearchBar component

import React, { Component } from 'react';
import axios from 'axios';

import Profile from './Profile';

class SearchBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fetchUser: {
        username: '',
        firstName: '',
        lastName: '',
        email: '',
        hobby: ''
      }
    }
    this.fetchUser = this.fetchUser.bind(this);
  }

  fetchUser() {
    axios.get('http://awesomeserver/users.username')
      .then( (response) => {
        console.log("response", response);
        this.setState({
          fetchUser: response.data
        });
        console.log("fetchUser", this.state.fetchUser);
      })
      .catch( (error) => {
        console.log(error);
      });  
  }

  render() {
    return (
      <div>
          <input placeholder="Enter in a username" />
          <button onClick={this.fetchUser}>Search</button>
          <Profile firstName={this.state.fetchUser.firstName} lastName={this.state.fetchUser.lastName} email={this.state.fetchUser.email} />
      </div>
    );
  }
}

export default SearchBar;  

请同时检查控制台中的response,以确保您拥有正确的对象。如果有的话,请在这里发布一些错误,谢谢!

答案 1 :(得分:0)

您正在点击搜索按钮调用fetchUsers函数,因此当您执行setState反应时,不会返回响应,而是使用setState设置状态变量中的数据渲染组件,它会将配置文件数据传递给Profile组件。

像这样编写 SearchBar 组件:

class SearchBar extends Component {

  constructor(){
      super();
      this.state = {
          profileDetails: {}
      }
      this.fetchUser = this.fetchUser.bind(this);
  }

  fetchUser() {
      axios.get('http://awesomeserver/users.username')
      .then((response) => {
          this.setState({profileDetails: response.data})
      })
      .catch((error) => {
          console.log(error);
      });
  }

   render() {
      return (
         <div>
             <input placeholder="Enter in a username" />
             <button onClick={this.fetchUser}>Search</button>
             <Profile {...this.state.profileDetails} />
         </div>
      );
   }
}

查看DOC了解 {...} 的详细信息。

答案 2 :(得分:0)

您可以制作类似的axios请求。 Axios结果是异步的,它不会从函数返回结果,因此this.fetchUsers.firstName等没有意义。调用该函数并将结果保存在axios回调中的状态,如

class SearchBar extends Component {
  state = {
        firstName: '',
        lastName: '',
        email: ''
  }
  fetchUser = () => {
      axios.get('http://awesomeserver/users.username')
            .then(res => {
                 return res.json()
            }).then(response => {
                  this.setState({firstName: response.firstName, lastName: response.lastName, email: response.email})
             })
  }

  render() {
    return (
      <div>
          <input placeholder="Enter in a username" />
          <button onClick={this.fetchUser}>Search</button>
          <Profile firstName={this.state.firstName} lastName={this.state.lastName} email={this.state.email} />
      </div>
    );
  }
}

export default SearchBar;