реагировать вызов функции - PullRequest
0 голосов
/ 30 ноября 2018

У меня есть API класса с функцией, которую я хочу вызвать в моем компоненте.

export default function(authentification){
axios.post('/login',params)
.then(response=> {
  localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
  localStorage.setItem(IS_AUTHENTICATED, true);
  this.setState({isAuthenticated:true});
})
.catch(error =>{
  const statusCode = error.response.status;
  if(statusCode === 401)
    errors.authentification = true;
  else if (statusCode === 404)
    errors.resource = true;
  else
    errors.server = true;

    this.setState({errors});
});
}

Я не нашел, как вызвать эту функцию в моем компоненте и как вернуть ее результатположить его в setState

Ответы [ 4 ]

0 голосов
/ 30 ноября 2018

Я реструктурировал свой код.Я не знаю, если это хорошая архитектура для работника.Но я еще не получил ответ в своем компоненте

Классовая аутентификацияAPI:

import axios from "axios";

const AuthentificationAPI = {
login(params){
    return  axios.post('/login',params);
},
}

export {AuthentificationAPI as default}

AuthentificationService:

import { ACCESS_TOKEN, IS_AUTHENTICATED } from "constants/constants.js";
import AuthentificationAPI from "api//authentificationAPI.js";

const AuthentificationService = {
login(params){
    let errors  = {};

    AuthentificationAPI.login(params).then(response => {
        localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
        localStorage.setItem(IS_AUTHENTICATED, true);

        return {isAuthenticated:true};
      })
      .catch(error => {
        const statusCode = error.response.status;

        if(statusCode === 401)
            errors.authentification = true;
        else if (statusCode === 404)
            errors.resource = true;
        else
            errors.server = true;

        return errors;
      });

    },
 }

 export {AuthentificationService as default}

Вызовите в моем компоненте:

  let resp = AuthentificationService.login(params);

  console.log(resp);
0 голосов
/ 30 ноября 2018

в файле .js создайте все нужные вам функции и экспортируйте их

let xxx = (authentification) => {
axios.post('/login',params)
.then(response=> {
  localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
  localStorage.setItem(IS_AUTHENTICATED, true);
  this.setState({isAuthenticated:true});
})
.catch(error =>{
  const statusCode = error.response.status;
  if(statusCode === 401)
    errors.authentification = true;
  else if (statusCode === 404)
    errors.resource = true;
  else
    errors.server = true;

    this.setState({errors});
});
}

export default xxx;

, затем импортируйте их туда, где вы хотите их использовать следующим образом -> импортируйте xxx из 'path';

0 голосов
/ 30 ноября 2018

Я должен протестировать различные решения, и ни одно из них не работает.Моя переменная всегда остается неопределенной

export function login(params){
const errors  = {};

axios.post('/login',params)
.then(response=> {
    localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
    localStorage.setItem(IS_AUTHENTICATED, true);

    return {isAuthenticated:true};
})
.catch(error =>{
    const statusCode = error.response.status;

    if(statusCode === 401)
        errors.authentification = true;
    else if (statusCode === 404)
        errors.resource = true;
    else
        errors.server = true;

    return errors;
});
}

В моем компоненте:

      const resp = login(params);
  console.log(resp);
0 голосов
/ 30 ноября 2018

Первое: отделите ваш setState от вашего вспомогательного метода API, например:

export default function(authentification){
  axios.post('/login',params)
  .then(response=> {
    localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
    localStorage.setItem(IS_AUTHENTICATED, true);
    return {status: "ok"}
  })
  .catch(error =>{
    const statusCode = error.response.status;
    if(statusCode === 401)
      errors.authentification = true;
    else if (statusCode === 404)
      errors.resource = true;
    else
      errors.server = true;
    return {status: "error", errors}
  });
}

Или, если вы хотите использовать синтаксис async / await в вашем методе API:

const authentification = async (params) => {
    const response = await axios.post('/login',params);
    const statusCode = response.status;
    if (statusCode >= 200 && statusCode < 300) {
        localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
        localStorage.setItem(IS_AUTHENTICATED, true);
        return {status: "ok"}
    }
    let errors = {};
    if (statusCode === 401) {
        errors.authentification = true;
    }
    else if (statusCode === 404) {
        errors.resource = true;
    }
    else {
        errors.server = true;
    }
    return {status: "error", errors}
}

export default authentification;

ЗатемВызовите API-функцию внутри componentDidMount() метода жизненного цикла вашего Компонента, например:

...
componentDidMount = async () => {
  let resp = await helperfunction();
  if (resp.status === "ok") {
    this.setState({isAuthenticated:true});
    return;
  }
  this.setState({resp.errors});
}
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...