您好,登錄后才能下訂單哦!
在React應(yīng)用中,狀態(tài)管理是一個重要的環(huán)節(jié),尤其是在復(fù)雜的工作流中。以下是一些關(guān)于React狀態(tài)管理的最佳實踐:
// 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>
組件包裹應(yīng)用,確保所有組件都能訪問到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應(yīng)用中的狀態(tài),提高應(yīng)用的性能和可維護(hù)性。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。