![](/img/trans.png)
[英]How to set a redux toolkit initial state to an array of object or localstorage with typescript?
[英]How do I connect to my state by ID params in Redux Toolkit when the data is an object not an array?
看看下面我的切片
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 是一個 object
我需要要么將state.mapdata
轉換為 Object,以便我可以按原樣使用選擇器,要么重新編碼選擇器,使其不使用.find()
function,因為這是一個數組 function。但是要么方式,它需要將數據中的 titleId 與參數中的 id 進行比較
很抱歉沒有提供可行的代碼。 我願意,但這里有大量的依賴項
你應該使用
state.mapdata = [action.payload, ...state.mapdata]
代替
state.mapdata = [action.payload, ...state]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.