看看我下面的切片
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const KEY = process.env.REACT_APP_API_KEY
const BASE_URL = process.env.REACT_APP_BASE_URL
const API = `${BASE_URL}/countrymap`
const initialState = {
mapdata:[],
status: 'idle',
error:null
}
export const fetchMapData = createAsyncThunk(
'mapdata/fetchMapData',
async (id) => {
try {
const response = await axios.get(
API,
{
headers: {
'Content-Type': 'application/json',
'X-API-KEY': KEY,
},
params: {
titleId: id,
}
}
)
return response.data.Item;
} catch (error) {
console.error('API call error:', error.message);
}
}
)
const mapSlice = createSlice({
name: 'mapdata',
initialState,
reducers:{
},
extraReducers(builder) {
builder
.addCase(fetchMapData.fulfilled, (state, action) => {
state.status = 'succeeded'
//This attempt to make it an array failed with the error
// that the state is not iterable
state.mapdata = [action.payload, ...state]
console.log("map payload: ", state.mapdata);
})
}
})
// SELECTORS
// This works for an array, but the data is originally coming
// in as an object instead
export const allMapData = (state, id) => state.mapdata.mapdata.find(item => item.title_id === id);
export default mapSlice.reducer
作為參考,請查看從兩個不同的 API 呼叫到來自兩個不同切片的兩個不同端點的這兩個控制臺日志。除了 Media 作為陣列回傳,而 map 是一個物件

我需要要么將其state.mapdata轉換為物件,以便我可以按原樣使用選擇器,要么重新編碼選擇器,使其不使用該.find()函式,因為那是一個陣列函式。但無論哪種方式,它都需要將資料中的titleId與params中的id進行比較
很抱歉沒有提供可行的代碼。我會,但這里有大量的依賴項
uj5u.com熱心網友回復:
你應該使用
state.mapdata = [action.payload, ...state.mapdata]
代替
state.mapdata = [action.payload, ...state]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/463266.html
標籤:javascript 反应 反应还原 redux 工具包
