React Reducer删除数据报错:state.pages.filter不是函数求助
Let's figure out why you're hitting that state.pages.filter is not a function error when deleting a page — it's a common mismatch between state structure and how you're updating it.
Problem Root Cause
The error tells us state.pages isn't an array when the DELETE_PAGE action runs. Here's what's happening:
- Your initial state sets
pages: [](an array) - But in the
GET_PAGESreducer case, you assignpages: payload— and from your component code, it's clear this payload is a pagination object (you're accessingpages.pageOfItemsto render items). So afterGET_PAGES,state.pagesbecomes an object instead of an array. WhenDELETE_PAGEtries to call.filter()on it, it throws an error because objects don't have that method.
Fix Option 1: Keep pages as an Array in State
If you want to stick with an array for pages (matching your initial state), adjust the GET_PAGES case to extract the actual items array from the pagination payload:
case GET_PAGES: return { ...state, page: null, pages: payload.pageOfItems, // Grab the array of pages from the pagination object pagination: payload, // Optional: store full pagination data if you need it (e.g., total pages) loading: false };
Then your existing DELETE_PAGE case will work as-is (since state.pages remains an array). You'll just need to update your component to use pages directly instead of pages.pageOfItems:
// In your component's JSX {pages.length > 0 ? ( <div className="row"> {/* ... */} {pages.map(post => ( <tr key={post._id}> {/* ... */} </tr> ))} </div> ) : ( <div className="nothingfound"> <div className="alert alert-danger">No pages found</div> </div> )}
Fix Option 2: Adjust State to Match the Pagination Object
If you want to keep the full pagination object in state.pages (to use properties like current page number or total items), update your state structure and reducer to work with the object:
- Update the initial state:
const initialState = { pages: { pageOfItems: [] }, // Now an object containing the items array page: null, loading: true, error: {} };
- Modify the
DELETE_PAGEcase to filter the nestedpageOfItemsarray:
case DELETE_PAGE: return { ...state, pages: { ...state.pages, // Preserve other pagination properties (e.g., totalCount) pageOfItems: state.pages.pageOfItems.filter(page => page._id !== payload) }, loading: false };
Your GET_PAGES case can stay unchanged (since you're assigning the full pagination object to pages), and your component code won't need any updates here.
Quick Validation Step
Double-check that your getPosts action creator is returning a payload with the correct structure (a pagination object containing pageOfItems array) when dispatching the GET_PAGES action. This ensures the data flowing into your reducer matches what you're expecting.
内容的提问来源于stack exchange,提问作者Kirasiris

