将多个参数从createAsyncThunk传递到我的页面



给定以下切片

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const KEY = process.env.REACT_APP_API_KEY
const URL = process.env.REACT_APP_BASE_URL
const API = `${URL}/interimtoptitles`
const initialState = {
carouseldata:{},
status: 'idle',  //'idle', 'loading', 'succeeded', 'failed'  
error:null
}
export const fetchCarouselData = createAsyncThunk(
'carouseldata/fetchCarouselData', 
async (rowTitle, sortingMetric, dateGranularity, weekStartDate) => { 
try {
const response = await axios.get(
API,
{
headers: {
'Content-Type': 'application/json',
'X-API-KEY': KEY,
},
params: {
rowTitle:         rowTitle,
sortingMetric:    sortingMetric,
dateGranularity:  dateGranularity,
weekStartDate:    weekStartDate
},
}
)
const loadedCarousel = response.data.Item;
console.log("loadedCarousel: ", loadedCarousel);
return loadedCarousel;
} catch (error) {
console.error('API call error:', error.message);
}
}
)
const carouselSlice = createSlice({
name: 'carouseldata',
initialState,
reducers:{},
extraReducers: {
[fetchCarouselData.pending]: (state, action) => {
state.status = "loading"
},
[fetchCarouselData.fulfilled]: (state, { payload }) => {
state.status = 'succeeded'
state.carouseldata = payload
},
[fetchCarouselData.rejected]: (state, action) => {
state.status = "failed"
},
}
})
// SELECTORS
export const getCarouselData = (state) => state.carouseldata.carouseldata;
export const getCarouselStatus = (state) => state.carouseldata.status;
export default carouselSlice.reducer

和查看页面(简化(

const [state, setState] = useState({
category: "Saved Titles",
metric: "liked",
granularity: "All Time",
startdate: convertDate(getPrevMonday(new Date(addDays(prevMonday, -7)))),
enddate: prevSunday, //all are required except this one
})
const {rowTitle, sortingMetric, dateGranularity, weekStartDate} = useParams();
const dispatch = useDispatch();
const carouseldata = useSelector(getCarouselData);
const status = useSelector(getCarouselStatus)
useEffect(() => { 
dispatch(fetchCarouselData({
rowTitle: state.category, 
sortingMetric: state.metric, 
dateGranularity: state.granularity, 
weekStartDate: state.startdate,
})); 
}, 
[
dispatch, 
state.category, 
state.metric, 
state.granularity, 
state.startdate, 
state.enddate, 
rowTitle, 
sortingMetric, 
dateGranularity, 
weekStartDate
]
);

如何将这些参数传递到视图?我习惯于用一个参数来做。通常是id,但从不和一群params在一起。const {rowTitle, sortingMetric, dateGranularity, weekStartDate} = groupParams;和在异步参数中传递groupParams也不起作用。

对参数进行硬编码可以使其工作,但我做不到。我需要将params作为道具传递,这样当视图中的状态发生变化时,它们就可以发生变化

您需要更改类似的代码

export const fetchCarouselData = createAsyncThunk(
'carouseldata/fetchCarouselData', 
async (arge) => { 
const {rowTitle, sortingMetric, dateGranularity, weekStartDate} = arge
try {
const response = await axios.get(

因为您作为对象通过

相关内容

  • 没有找到相关文章

最新更新