gpt4 book ai didi

javascript - 当我使用 createAsyncThunk 时,action.payload 返回未定义

转载 作者:行者123 更新时间:2023-12-05 04:23:04 29 4
gpt4 key购买 nike

我是 Redux/Redux-Toolkit 的新手,我一直在尝试使用 RTK 为异步方法提供的 createAsyncThunk 方法获取一些数据,但我遇到了一些问题,我的有效负载刚刚“完成”返回空值。

我还能够 console.log 仅出于测试目的获取的数据,因此我知道我能够获取它。

我不确定这是我遇到的 javascript 问题还是 Redux 问题,所以非常感谢您的帮助!

如果有人有兴趣提供帮助,这里是我手上的一些代码片段!

// searchSlice.js

const fetchRequest = () => {
return fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
Authorization: 'Basic ' + btoa(client_id + ':' + client_secret),
},
body: 'grant_type=client_credentials',
})
}

// searchSlice.js

export const getArtistByQuery = createAsyncThunk('search/getArtistByQuery', async (query) => {
await fetchRequest()
.then((result) => result.json())
.then((data) => {
const token = data?.access_token;
const spotify = new SpotifyWebApi();

spotify.setAccessToken(token);
spotify.searchArtists(query, {limit: 10})
.then((data) => {
return data?.artists?.items
})
})
})

// Where I dispatch 
// SearchInput.js

const handleSubmit = (e) => {
e.preventDefault();
dispatch(getArtistByQuery(query));
console.log(artists);
setQuery("");
}

return (
<Flex textAlign="center" m={5}>
<form onSubmit={handleSubmit}>
<FormControl>
<Input mb={5} type="text" onChange={handleChange} placeholder='Enter artist' size="md"/>
<Button type="submit">Click Me</Button>
</FormControl>
</form>
</Flex>
)
}

// createSlice

const artistsSlice = createSlice({
name: 'artists',
initialState,
extraReducers: builder => {
builder.addCase(getArtistByQuery.pending, state => {
state.loading = true
})
builder.addCase(getArtistByQuery.fulfilled, (state, action) => {
state.loading = false
console.log("Payload: " + action.payload)
state.artists = action.payload
state.error = ''
})
builder.addCase(getArtistByQuery.rejected, (state, action) => {
state.loading = false
state.artists = {}
state.error = action.error.message
})
}
})

// initialState

const initialState = {
loading: false,
artists: {},
error: ''
}

// store.js

export const store = configureStore({
reducer: {
artistsSlice: artistReducer,
},
});

最佳答案

而不是这个

export const getArtistByQuery = 
createAsyncThunk('search/getArtistByQuery', async (query) => {
await fetchRequest().then

应该是这样

export const getArtistByQuery = 
createAsyncThunk('search/getArtistByQuery', async (query) => {
return await fetchRequest().then()

关于javascript - 当我使用 createAsyncThunk 时,action.payload 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73793424/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com