const redirectURL = 'http://localhost:3000/';
const authorizePage = `https://accounts.spotify.com/authorize?response_type=token&client_id=${clientID}`
+`&redirect_uri=${redirectURL}&scope=playlist-modify-public`;
export const searchTerm = createAsyncThunk('musics/searchTerm',
async (term, {dispatch, getState}) => {
let accessToken = getState().result.accessToken;
if (!accessToken) {
window.location.replace(authorizePage);
let tempToken = /access_token=(.*?)&/.exec(window.location.href);
let expireTime = /expires_in=(.*)/.exec(window.location.href);
dispatch(setAccessToken(tempToken[1]));
window.setTimeout(() => {
console.log('here is mistake right?');
dispatch(setAccessToken(''));
}, Number(expireTime[1]) * 1000);
window.history.pushState('Access Token', null, '/')
}
return await fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: {Authorization: `Bearer ${accessToken}`}
})
.then(res => {
if (res.ok)
return res.json();
}, networkErr => console.log(networkErr.message)
)
.then(jsonResponse => {
if (jsonResponse && jsonResponse.tracks) {
console.log(jsonResponse, 'here');
}
});
}
);
export const resultSlice = createSlice({
name: 'result',
initialState: { accessToken: '', searchResult: [] },
reducers: {
setAccessToken: (state, action) => {
state.accessToken = action.payload;
console.log('here we go', action.payload);
}
},
extraReducers(builder) {
builder
.addCase(searchTerm.fulfilled, (state, action) => {
console.log(action.payload);
})
.addCase(searchTerm.rejected, (state, action) => {
})
}
});
const { setAccessToken } = resultSlice.actions;
首先,我检查状态中是否存在accessToken。如果不存在,我将用户重定向到spotify页面进行授权,并从location.href获取accessToken。我试图将tempToken保存到reducer中,但在调度它之后,它就不见了,而且一次又一次地发生。它正在重新渲染,我能找到其他方法来防止它不发生吗?