结构:
ApiService.js
components/
TrackComponent.jsxTrackComponent.jsx
我在render()中的React中有这样的表单,它触发了一个命中一个端点的事件:
<form onSubmit={ (event) => this.handleEditPlaylist(event) }>
<div className="field">
<input
name="artist"
className="input is-dark is-large"
type="text"
/>
</div>
</form>处理功能:
handleEditPlaylist(event) {
event.preventDefault();
const formType = this.props.formType
var headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
const {userId} = this.props
const data = {
value: this.state.formData.value,
spotify_token: this.props.spotifyToken
};
const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/handle_edit_playlist/${this.state.artist}/${userId}`;
axios.post(url, data, {headers: headers})
.then((res) => {
console.log(data);
if(data){this.clearForm();}
})
.catch((err) => {
});
axios.get(url, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
}).then((res) => {
console.log(res.data);
this.setState({
seeds: res.data.data[0].seeds,
artist: res.data.data[0].artist,
})
})
};这个很管用。
组件内部的
Api实例
现在,为了处理具有两个端点的访问令牌,必须在上面的组件中实例化这个axios拦截器。
import Axios from 'axios';
class ApiService {
constructor() {
this.axios = Axios.create();
this.axios.interceptors.response.use(null, this.authInterceptor.bind(this));
this.get = this.axios.get.bind(this.axios);
this.post = this.axios.post.bind(this.axios);
}
async authorize() {
console.log('Async in authorize')
const { accessToken } = await this.axios.post('/get_token/1', {});
this.setAccessToken(accessToken);
return accessToken; // return it to the component that invoked it to store in some state
}
async getTrack(userId, spotifyToken, artist) { // <---------------------------
console.log('getAroma in ApiService', userId, spotifyToken, artist)
return this.axios.get(
`${process.env.REACT_APP_WEB_SERVICE_URL}/get-tracks/${artist}/${userId}/${spotifyToken}`
);
}
async updateAccessToken(userId) {
const { accessToken } = await this.axios.post(`/refresh-token/1`, {});
this.setAccessToken(accessToken);
}
(...)
export const apiService = new ApiService(); // this is a single instance of the service, each import of this file will get it我希望上面的同一个onSubmit事件也触发拦截器实例化调用。我自己也可以这样做:
import {apiService} from '../ApiService';
async getTrack(event) {
if (this.props.isAuthenticated) {
const {userId, spotifyToken} = this.props;
const {artist} = this.state.artist
const aromaticTracks = await apiService.getTracks(userId, spotifyToken, artist);
this.setState({newTracks});
} else {
this.setState({newTracks: []});
}
}如果我将这个异步getTrack插入到handleEditPlaylist中,就在表单提交之后,如下所示:
(...)
axios.post(url, data, {headers: headers})
.then((res) => {
this.getTrack(); // <----------- HERE
console.log(data);
if(data){this.clearForm();}
})
(...)对于表单提交的值(艺术家),我在async getTrack console.log('getTrack in ApiService', userId, spotifyToken, artist)**,中得到“未定义”,但打印在** console.log(data) 中提交的值,如下所示
如何正确处理这个拦截器onSubmit?
发布于 2020-04-29 16:26:29
代码中唯一的问题是,您正在尝试从已经在访问的状态中重构一个值。
async getTrack(event) {
if (this.props.isAuthenticated) {
const {userId, spotifyToken} = this.props;
const {artist} = this.state; // this needs to be this.state and not this.state.artist
const aromaticTracks = await apiService.getTracks(userId, spotifyToken, artist);
this.setState({newTracks});
} else {
this.setState({newTracks: []});
}
}destructuring赋值语法是一个JavaScript表达式,可以将数组的值或对象的属性解压缩到不同的变量中。
https://stackoverflow.com/questions/61449224
复制相似问题