大家好,我是老十三,一名前端開發工程師。在前端的江湖中,React與Vue如同兩大武林門派,各有千秋。今天,我將帶你進入這兩大框架的奧秘世界,共同探索組件生命周期、狀態管理、性能優化等核心難題的解決之道。無論你是哪派弟子,掌握雙修之術,才能在前端之路上游刃有余。準備好啟程了嗎?
掌握了DOM渡劫的九道試煉后,是時候踏入現代前端的核心領域——框架修行。在這條充滿挑戰的雙修之路上,我們將探索React與Vue這兩大主流框架的精髓,以及它們背后的設計哲學。
?? 第一難:生命周期 - 組件的"六道輪回"
問題:組件從創建到銷毀經歷了哪些階段?如何在正確的生命周期階段執行相應操作?
深度技術:
組件生命周期是前端框架的核心概念,描述了組件從創建、更新到銷毀的完整過程。理解生命周期,意味著掌握了何時獲取數據、何時操作DOM以及何時清理資源。
React和Vue在生命周期設計上既有相似之處,也有顯著區別。React強調函數式理念,推動Hooks模式;Vue則提供更直觀的選項式API,同時也支持組合式API。無論哪種方式,合理使用生命周期鉤子都是構建高性能應用的關鍵。
代碼示例:
// React Hooks生命周期
function HooksLifecycle() {const [count, setCount] = React.useState(0);const [userId, setUserId] = React.useState(1);const prevUserIdRef = React.useRef();// 相當于constructor + componentDidMount + componentDidUpdateReact.useEffect(() => {console.log('組件掛載或更新');// 設置定時器const timer = setInterval(() => {setCount(c => c + 1);}, 1000);// 返回清理函數,相當于componentWillUnmountreturn () => {console.log('組件卸載或更新前清理');clearInterval(timer);};}, []); // 空依賴數組,僅在掛載和卸載時執行// 監聽特定依賴變化React.useEffect(() => {console.log('userId發生變化,獲取新用戶數據');fetchUserData(userId);}, [userId]); // 僅當userId變化時執行// 模擬getDerivedStateFromPropsReact.useEffect(() => {if (prevUserIdRef.current !== userId) {console.log('從props派生狀態');}prevUserIdRef.current = userId;});// 模擬componentDidUpdate - 比較前后值const prevCountRef = React.useRef();React.useEffect(() => {const prevCount = prevCountRef.current;if (prevCount !== undefined && prevCount !== count) {console.log('count從', prevCount, '變為', count);}prevCountRef.current = count;});// 使用布局效果,在DOM變更后同步觸發React.useLayoutEffect(() => {console.log('DOM更新后立即執行,瀏覽器繪制前');// 獲取DOM測量或直接操作DOM});return (<div><h1>Hooks計數器: {count}</h1><button onClick={() => setCount(count + 1)}>增加</button><button onClick={() => setUserId(userId + 1)}>切換用戶</button></div>);
}// Vue 3組合式API生命周期
import { ref, onMounted, onBeforeMount, onUpdated, onBeforeUpdate, onBeforeUnmount, onUnmounted, watch } from 'vue';const LifecycleDemo = {setup() {const count = ref(0);const message = ref('Hello Vue 3');onBeforeMount(() => {console.log('1. onBeforeMount: 組件掛載前');});onMounted(() => {console.log('2. onMounted: 組件已掛載');// 適合進行DOM操作、網絡請求、訂閱事件const timer = setInterval(() => {count.value++;}, 1000);// 清理函數onBeforeUnmount(() => {clearInterval(timer);});});onBeforeUpdate(() => {console.log('3. onBeforeUpdate: 組件更新前');});onUpdated(() => {console.log('4. onUpdated: 組件已更新');});onBeforeUnmount(() => {console.log('5. onBeforeUnmount: 組件卸載前');});onUnmounted(() => {console.log('6. onUnmounted: 組件已卸載');});// 監聽數據變化watch(count, (newValue, oldValue) => {console.log(`count從${oldValue}變為${newValue}`);});return {count,message};}
};
?? 第二難:狀態管理 - 數據的"太極之道"
問題:如何優雅地管理應用狀態?Redux和Vuex各有什么特點?
深度技術:
狀態管理是前端應用的核心挑戰之一。Redux遵循嚴格的單向數據流和不可變數據原則,強調純函數reducer;Vuex則采用更貼近Vue的響應式設計。理解這兩種范式的差異和適用場景,是框架修行的關鍵一步。
代碼示例:
// Redux Toolkit示例
import { createSlice, configureStore } from '@reduxjs/toolkit';// 創建slice
const todoSlice = createSlice({name: 'todos',initialState: {items: [],filter: 'all'},reducers: {addTodo: (state, action) => {state.items.push({id: Date.now(),text: action.payload,completed: false});},toggleTodo: (state, action) => {const todo = state.items.find(todo => todo.id === action.payload);if (todo) {todo.completed = !todo.completed;}},setFilter: (state, action) => {state.filter = action.payload;}}
});// 導出actions
export const { addTodo, toggleTodo, setFilter } = todoSlice.actions;// 創建store
const store = configureStore({reducer: {todos: todoSlice.reducer}
});// React組件中使用Redux Toolkit
import { useSelector, useDispatch } from 'react-redux';function TodoApp() {const dispatch = useDispatch();const todos = useSelector(state => state.todos.items);const filter = useSelector(state => state.todos.filter);const [newTodo, setNewTodo] = React.useState('');const handleSubmit = e => {e.preventDefault();if (!newTodo.trim()) return;dispatch(addTodo(newTodo));setNewTodo('');};return (<div><h1>Todo應用</h1><form onSubmit={handleSubmit}><inputvalue={newTodo}onChange={e => setNewTodo(e.target.value)}placeholder="添加新任務"/><button type="submit">添加</button></form><div><button onClick={() => dispatch(setFilter('all'))}>全部</button><button onClick={() => dispatch(setFilter('active'))}>進行中</button><button onClick={() => dispatch(setFilter('completed'))}>已完成</button><span>當前: {filter}</span></div><ul>{todos.map(todo => (<likey={todo.id}style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}onClick={() => dispatch(toggleTodo(todo.id))}>{todo.text}</li>))}</ul></div>);
}// Pinia示例
import { defineStore } from 'pinia';export const useTodoStore = defineStore('todos', {state: () => ({items: [],filter: 'all'}),getters: {visibleTodos: (state) => {switch (state.filter) {case 'active':return state.items.filter(todo => !todo.completed);case 'completed':return state.items.filter(todo => todo.completed);default:return state.items;}}},actions: {addTodo(text) {this.items.push({id: Date.now(),text,completed: false});},toggleTodo(id) {const todo = this.items.find(todo => todo.id === id);if (todo) {todo.completed = !todo.completed;}},setFilter(filter) {this.filter = filter;}}
});// Vue組件中使用Pinia
import { useTodoStore } from './stores/todo';const TodoApp = {setup() {const store = useTodoStore();const newTodo = ref('');const handleSubmit = () => {if (!newTodo.value.trim()) return;store.addTodo(newTodo.value);newTodo.value = '';};return {store,newTodo,handleSubmit};},template: `<div><h1>Todo應用</h1><form @submit.prevent="handleSubmit"><inputv-model="newTodo"placeholder="添加新任務"/><button type="submit">添加</button></form><div><button @click="store.setFilter('all')">全部</button><button @click="store.setFilter('active')">進行中</button><button @click="store.setFilter('completed')">已完成</button><span>當前: {{ store.filter }}</span></div><ul><liv-for="todo in store.visibleTodos":key="todo.id":style="{ textDecoration: todo.completed ? 'line-through' : 'none' }"@click="store.toggleTodo(todo.id)">{{ todo.text }}</li></ul></div>`
};
?? 第三難:組件通信 - 數據的"乾坤大挪移"
問題:在React和Vue中,如何實現組件之間的數據傳遞和通信?有哪些最佳實踐?
深度技術:
組件通信是前端開發中的核心問題。React和Vue提供了多種組件通信方式,從簡單的props傳遞到復雜的狀態管理,從事件總線到上下文共享。理解這些通信方式的適用場景和最佳實踐,是構建可維護應用的關鍵。
代碼示例:
// React組件通信示例// 1. Props傳遞 - 父子組件通信
function ParentComponent() {const [count, setCount] = useState(0);return (<div><h1>父組件</h1><ChildComponent count={count} onIncrement={() => setCount(c => c + 1)} /></div>);
}function ChildComponent({ count, onIncrement }) {return (<div><p>子組件接收到的count: {count}</p><button onClick={onIncrement}>增加</button></div>);
}// 2. Context API - 跨層級組件通信
const ThemeContext = React.createContext('light');function ThemeProvider({ children }) {const [theme, setTheme] = useState('light');const toggleTheme = () => {setTheme(prev => prev === 'light' ? 'dark' : 'light');};return (<ThemeContext.Provider value={{ theme, toggleTheme }}>{children}</ThemeContext.Provider>);
}