反应:静态方法总是返回未定义的

时间:2019-05-02 12:20:21

标签: javascript reactjs static

我在使用airbnb配置的ESLint的React中使用静态方法时遇到问题。我有这样的服务,既用于在系统中创建用户,又用于获取创建用户表单的所有字段值。服务看起来像这样:

import axios from 'axios';

import ServiceException from './ServiceException';

class CreateUserServiceException extends ServiceException {}

class CreateUserService {
  constructor(config) {
    this.apiUrl = config.API_URL;
    this.userDomain = config.USER_DOMAIN;
  }

  static getFormFields() {
    return [
      {
        id: 'username',
        type: 'text',
        title: 'E-postadress',
        placeholder: 'Användarnamn',
        mandatory: true,
        extra: '',
      },
      {
        id: 'password',
        type: 'password',
        title: 'Lösenord',
        placeholder: 'Lösenord',
        mandatory: true,
        extra: '',
      },
    ];
  }

  async createUser(data) {
    try {
      await axios.post(`${this.apiUrl}/users/${this.userDomain}`, data, { withCredentials: true });
    } catch ({ response }) {
      throw new CreateUserServiceException(
        response.status, 'Failed to create user', response.data,
      );
    }
  }
}

export default CreateUserService;

我也有一个jsx控制器来创建表单。该控制器通过其属性获取服务。控制器如下所示:

import React from 'react';

import './index.css';

class CreateUserController extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      formFields: [],
      userData: {},
    };

    this.onCreate = this.onCreate.bind(this);
    this.onLoad = this.onLoad.bind(this);
  }

  async componentDidMount() {
    await this.onLoad();
  }

  async onLoad() {
    const { createUserService } = await this.props;
    const { getFormFields } = createUserService;
    const formFields = getFormFields || []; // ALWAYS RETURNS UNDEFINED
    const userData = {};

    console.log(formFields); // ALWAYS DISPLAYS []

    formFields.forEach((field) => {
      userData[field.id] = '';
    });

    this.setState({ formFields, userData });
  }

  async onCreate(e) {
    e.preventDefault();

    const { userData } = this.state;
    console.log(userData);
  }

  render() {
    const { userData, formFields } = this.state;

    return (
      <section className="create-user-controller">
        <h1>Skapa ny användare</h1>
        <form
          className="centered-container"
          action=""
          noValidate
          onSubmit={this.onCreate}
        >
          <table>
            <tbody>
              {formFields.map(field => (
                <tr key={field.id}>
                  <td>{field.title}</td>
                  <td>
                    <input
                      value={userData[field.id]}
                      onChange={e => this.setState({
                        userData: { ...userData, [field.id]: e.target.value },
                      })}
                      className={`create-${field.id}`}
                      name={field.id}
                      placeholder={field.placeholder}
                      type={field.type}
                    />
                  </td>
                  <td>{field.extra}</td>
                </tr>
              ))}
              <tr>
                <td colSpan={3}>* obligatoriskt</td>
              </tr>
            </tbody>
          </table>
          <input type="submit" className="btn btn-green" value="Skapa användare" />
        </form>
      </section>
    );
  }
}

export default CreateUserController;

我的问题是const formFields = getFormFields || [];始终变为[],这意味着getFormFields始终返回未定义。

如果我从服务中的static中删除了getFormFields(),并使用const formFields = createUserService.getFormFields();对其进行了调用,则效果很好,但是ESLint抱怨ESLint: Expected 'this' to be used by class method 'getFormFields'. (class-methods-use-this)

有人知道如何解决吗?

1 个答案:

答案 0 :(得分:1)

import CreateUserService from './CreateUserService';
...
async onLoad() {
    ...
    const formFields = CreateUserService.getFormFields() || [];
    ...
}

应该做到这一点! 请注意,使用类名称调用了静态函数。头也必须正确导入(我不知道您的路径...)