如何同步react
同步 React 状态的方法
使用 useState 和 useEffect 钩子来管理状态和副作用。useState 用于声明状态变量,useEffect 用于在状态变化时执行同步操作。

import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
使用 Context API 同步全局状态
创建上下文和提供者来共享状态,使多个组件可以访问和同步同一状态。

import React, { createContext, useContext, useState } from 'react';
const CountContext = createContext();
function CountProvider({ children }) {
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={{ count, setCount }}>
{children}
</CountContext.Provider>
);
}
function Counter() {
const { count, setCount } = useContext(CountContext);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
function App() {
return (
<CountProvider>
<Counter />
</CountProvider>
);
}
使用 Redux 进行状态管理
安装 Redux 和 React-Redux,创建 store 和 reducer 来管理全局状态。
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
</div>
);
}
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
使用自定义 Hook 同步状态
创建自定义 Hook 来封装状态逻辑,实现跨组件的状态同步。
import { useState, useEffect } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
useEffect(() => {
console.log(`Count is now: ${count}`);
}, [count]);
return { count, increment };
}
function CounterA() {
const { count, increment } = useCounter();
return (
<div>
<p>Counter A: {count}</p>
<button onClick={increment}>Increment A</button>
</div>
);
}
function CounterB() {
const { count, increment } = useCounter();
return (
<div>
<p>Counter B: {count}</p>
<button onClick={increment}>Increment B</button>
</div>
);
}
function App() {
return (
<div>
<CounterA />
<CounterB />
</div>
);
}





