ReactJS |无法在ComponentDidMount上获取数据

时间:2019-03-08 14:49:51

标签: javascript reactjs api axios state

我正在从本地Mock-API获取数据。服务器发送的数据具有以下格式:

module.exports = [
  {
    username: "george",
    email: "george@test.com",
    group: "foo",
    loggedIn: true
  },
  {
    username: "nick",
    email: "nick@test.com",
    group: "bar",
    loggedIn: false
  }
];

基本上,您可以看到用户列表。每个用户的唯一ID是他们的username。在我的ReactJS U.I中,我有一个用户列表。当我单击其中一个用户时,我将重定向到新页面,并且url会根据我单击的用户的数量而更改

但是我无法获取有关该用户的任何数据。我得到一个用JSON.Stringify打印的空字符串。这是我的编码:

/* eslint-disable react/prefer-stateless-function */
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';

import PageHeader from './PageHeader';
import Breadcrumb from './Breadcrumb';
import Role from 'shared/common/enums/Role';

import { getUser } from '../../config/service';

class UserDetailsScreen extends Component {
  state = {
    inEditMode: false,
    user: {},
    error: null
  };

  componentDidMount() {
    this.fetchUser();
  }

  fetchUser = () => {
    getUser().then(({ data }) => {
      this.setState({ user: data });
    });
  };

  render() {
    const {user } = this.state;
    return (
      <div className="container-fluid">
        <div><pre>{JSON.stringify(user, null, 2)}</pre></div>
        {user && (
          <Fragment>
            <Breadcrumb
              items={[
                {
                  name: 'Users',
                  url: 'users'
                },
                {
                  name: user.username,
                  url: `${user.username}`
                }
              ]}
            />
            <h1 className="heading-title">{user.username}</h1>
        )}
      </div>
    );
  }
}

export default UserDetailsScreen;

getUser()是在我的本地端点上侦听的函数。这是端点:GET_USER: name => http://localhost:5000/api/user/ $ {name} ,

这是getUser()

export const getUser = name => {
  const options = {
    method: httpMethod.GET,
    url: endpoint.GET_USER(name)
  };
  return instance(options);
};

这是Dyson Server实例,用于使用用户名作为唯一ID来获取特定用户:

const users = [
    {
    username: "george",
    email: "george@test.com",
    group: "foo",
    loggedIn: true
  },
  {
    username: "nick",
    email: "nick@test.com",
    group: "bar",
    loggedIn: false
  }
]

module.exports = {
  path: '/api/user/:username',
  method: 'GET',
  template: (pathParameters) => {
    return users.find((user) => {
      return user.username === pathParameters.username;
    })
  }
};

您看到任何错误吗?

1 个答案:

答案 0 :(得分:1)

您没有在getUser()中传递'name'参数,请尝试传递:

fetchUser = () => {
    getUser('USERNAME').then(({ data }) => {
      this.setState({ user: data });
    });
  };