2017-09-01 7 views
0

私はREACT/AXIOSで曇りのあるAPIを使用していますが、Axiosコールの前と後にデータを引き出す方法が不思議でした。私が抱えている問題は、コールバックを1つ使用すると、1つまたは他のデータのみを入れることができるということです。 2つのコールバックを使用することは可能ですか?2つのコールバック機能を実行するにはどうすればよいですか?

これとは別の方法をとるべきですか?

私が望むのは、アップロードの進行を引き出し、その値を状態に保存できることです。私の唯一の問題は、これを行う正しい方法がわからないことです。私はonUploadProgressファンクションの中でそれを行う必要があります。ここで

はコードです:コンポーネントで

機能:

uploadImage(files) { 
    const image = files[0]; 

    const cloudName = 'hyszj0vmt'; 
    const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`; 

    const apiSecret = '***********'; 
    const uploadPreset = '**************'; 
    const timestamp = Date.now()/1000; 
    const paramStr = `timestamp=${timestamp}&upload_preset=${uploadPreset}${apiSecret}`; 
    const signature = sha1(paramStr); 
    const params = { 
     api_key: '*******', 
     timestamp: timestamp, 
     upload_preset: uploadPreset, 
     signature: signature 
    }; 

    APIManager.upload(url, image, params, (err, response) => { 
     if (err) { 
     console.log(`UPLOAD ERROR: ${err}`); 
     return; 
     } 

     const imageUrl = response['secure_url']; 
     let updatedProfile = Object.assign({}, this.state.updated); 
     updatedProfile['image'] = imageUrl; 

     this.setState({ 
     updated: updatedProfile 
     }); 
    }); 
    } 

APIManager機能:これについて

upload: (endpoint, file, params, callback) => { 
    let fd = new FormData(); 

    fd.append('file', file); 
    Object.keys(params).forEach(key => { 
     fd.append(key, params[key]); 
    }); 

    const config = { 
     headers: { 'X-Requested-With': 'XMLHttpRequest' }, 
     onUploadProgress: progressEvent => { 
     const progress = Math.round(
      progressEvent.loaded * 100.0/progressEvent.total 
     ); 

     console.log(progress + '%'); 
     } 
    }; 

    axios 
     .post(endpoint, fd, config) 
     .then(response => { 
     const { data } = response; 
     callback(null, data); 
     }) 
     .catch(err => { 
     callback(err, null); 
     }); 
    } 
}; 

答えて

0

どのように?

upload: (endpoint, file, params, callback, callbackProgress) => { 
    ... 

    const config = { 
     headers: { 'X-Requested-With': 'XMLHttpRequest' }, 
     onUploadProgress: progressEvent => { 
     const progress = Math.round(
      progressEvent.loaded * 100.0/progressEvent.total 
     ); 
     callbackProgress(progress); 
     } 
    }; 

    ... 
}); 

使用法:

APIManager.upload(url, image, params, (err, response) => { 
    ... 
}, (progress) => { 
    console.log(progress); 
}); 
+0

私はAPIManager機能でこれを呼ぶだろうか? –

+0

どういう意味ですか?それは実際にはAPIManager関数にある – luschn

+1

は、使用のためのコードを追加しました – luschn

関連する問題