针对React的GET上的Axios回调

时间:2017-06-13 17:33:10

标签: reactjs axios

我正在尝试显示加载微调器,而axios get请求正在进行,并且这样做我相信我需要来自请求的回调。我在componentDidMount()中调用get请求,如下所示:

componentDidMount() {
  this.props.fetchCloudProperties( () => {
    this.setState( { dim : false } );
  } );
}

希望在检索数据时,调光器(微调器)将根据seState调用消失。我已经回复过帖子了,但是从来没有用过get来做过。我对数据的获取操作是:

export function fetchCloudProperties( callback ) {
  const VARIABLE_URL = '/cloud/properties';
  const request      = axios.get( `${ROOT_URL}${VARIABLE_URL}` )
    .then( request => {
      return ({
        type    : FETCH_CPS,
        payload : request
      });
    } ).catch( ( error ) => {
      console.log( error );
    } )
}

现在控制台正在抱怨'操作必须是普通对象'我不确定这意味着什么,但我也看到它抱怨未经处理的拒绝'所以不太确定。

编辑:我有一个使用回调的createCloudProperty方法,它运行正常:

export function createCloudProperty( values, callback ) {
  const VARIABLE_URL = '/cloud/property';
  const request      = axios.post( `${ROOT_URL}${VARIABLE_URL}`, values )
    .then( () => callback() );

  return ({
    type    : CREATE_CP,
    payload : request
  });
}

来自:

onSubmit( values ) {
  this.props.createCloudProperty( values, () => {
    this.props.history.push( '/cloudproperties' );
  } );
}

1 个答案:

答案 0 :(得分:0)

您无法传递请求/响应,因为它不是普通对象。您应该使用响应数据。

export function fetchCloudProperties( callback ) {
  const VARIABLE_URL = '/cloud/properties';
  const request      = axios.get( `${ROOT_URL}${VARIABLE_URL}` )
    .then( response => {
      return ({
        type    : FETCH_CPS,
        payload : response.data
      });
    } ).catch( ( error ) => {
      console.log( error );
    } )
}