如何使用ngrx/store结合@Input属性初始化模板?
Got it, let's get your component to display the initial category state right when it loads—since your addCategory test is already working, we just need to make sure the reducer's starting state is properly set up and fetched by your component. Here's the step-by-step breakdown:
1. Define Your Initial Category State
First, create an initial set of AdminCategory instances that matches your AppState type. This is what your component will see on load:
// In your reducer.ts file export interface AppState { categoryState: AdminCategory[] } export class AdminCategory { id: number; name: string; parentId: number; constructor(id: number, name: string, parentId: number) { this.id = id; this.name = name; this.parentId = parentId; } } // Create initial category data const initialCategories: AdminCategory[] = [ new AdminCategory(1, "Main Category", 0), new AdminCategory(2, "Subcategory A", 1), // Add more default categories as needed ]; // Define the full initial AppState const initialAppState: AppState = { categoryState: initialCategories };
2. Update Your Reducer to Use the Initial State
Make sure your reducer function returns the initial state when it first runs (i.e., when no action has been dispatched yet). Here's how to integrate it with your existing ADD_CATE action:
export const ADD_CATE = 'ADD_CATE'; export function categoryReducer(state: AppState = initialAppState, action: any): AppState { switch (action.type) { case ADD_CATE: // Existing logic to add a new category return { ...state, categoryState: [...state.categoryState, action.payload] }; default: // Return initial state (or current state) for unrecognized actions return state; } }
3. Fetch and Render the Initial State in Your Component
Use Redux's selector hook (like useSelector for React) to pull the initial state into your component when it mounts:
// In your component file import { useSelector } from 'react-redux'; import { AppState } from './reducer'; export default function CategoryList() { // Grab the initial category state from the store const categories = useSelector((state: AppState) => state.categoryState); return ( <div className="category-container"> <h3>Current Categories</h3> <ul> {categories.map(category => ( <li key={category.id}> {category.name} (Parent ID: {category.parentId}) </li> ))} </ul> {/* Your addCategory form/button can go here */} </div> ); }
Quick Checks to Ensure It Works
- Double-check that your Redux store is configured with this reducer (either via
createStoreor Redux Toolkit'sconfigureStore). - If you're using Redux Toolkit, you can simplify the reducer with
createSlice, but the core idea of defining an initial state remains the same.
Now when your component loads, it'll immediately render the initial categories you defined in the reducer—no need to trigger addCategory first!
内容的提问来源于stack exchange,提问作者minizibi

