您好,登錄后才能下訂單哦!
在React應用中,狀態管理是一個重要的環節,尤其是在復雜的工作流中。以下是一些關于React狀態管理的最佳實踐:
// actionTypes.js
export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO';
createSlice
,減少樣板代碼。// todosSlice.js
import { createSlice } from '@reduxjs/toolkit';
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
addTodo: (state, action) => {
state.push(action.payload);
},
deleteTodo: (state, action) => {
state.filter(todo => todo.id !== action.payload);
},
},
});
export const { addTodo, deleteTodo } = todosSlice.actions;
export default todosSlice.reducer;
// todosSlice.js (with Redux Thunk)
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
export const fetchTodos = createAsyncThunk('todos/fetchTodos', async () => {
const response = await axios.get('/api/todos');
return response.data;
});
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchTodos.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchTodos.fulfilled, (state, action) => {
state.status = 'succeeded';
state.todos = action.payload;
})
.addCase(fetchTodos.rejected, (state, action) => {
state.status = 'failed';
});
},
});
export const { fetchTodos } = todosSlice.actions;
export default todosSlice.reducer;
// selectors.js
import { createSelector } from '@reduxjs/toolkit';
const selectTodos = (state) => state.todos;
const selectActiveTodos = (state) => selectTodos(state).filter(todo => todo.active);
export const selectTodosByStatus = (state, status) => {
return selectTodos(state).filter(todo => todo.status === status);
};
<Provider>
組件包裹應用,確保所有組件都能訪問到Redux store。useSelector
和useDispatch
Hooks連接React和Redux。// TodoList.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { deleteTodo } from './todosSlice';
const TodoList = () => {
const todos = useSelector(selectTodos);
const dispatch = useDispatch();
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.text}
<button onClick={() => dispatch(deleteTodo(todo.id))}>Delete</button>
</li>
))}
</ul>
);
};
export default TodoList;
// store.js
import { configureStore } from '@reduxjs/toolkit';
import todosReducer from './todosSlice';
const store = configureStore({
reducer: {
todos: todosReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [fetchTodos], // 忽略異步操作的序列化檢查
},
}),
});
export default store;
通過遵循這些最佳實踐,可以有效地管理React應用中的狀態,提高應用的性能和可維護性。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。