react数据如何设置
在React中设置数据
React中数据管理主要通过state和props实现。state用于组件内部数据,props用于父子组件间数据传递。

使用useState设置组件内部数据
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
使用props传递数据
父组件传递数据给子组件:
function ParentComponent() {
const data = "Hello from parent";
return <ChildComponent message={data} />;
}
function ChildComponent({ message }) {
return <p>{message}</p>;
}
使用useReducer管理复杂状态
import React, { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}
使用Context跨组件共享数据
import React, { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <div>Current theme: {theme}</div>;
}
使用外部状态管理库
Redux示例:
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
function counterReducer(state = { value: 0 }, action) {
switch (action.type) {
case 'counter/incremented':
return { value: state.value + 1 }
default:
return state
}
}
const store = createStore(counterReducer);
function Counter() {
const count = useSelector(state => state.value)
const dispatch = useDispatch()
return (
<div>
<span>{count}</span>
<button onClick={() => dispatch({ type: 'counter/incremented' })}>
Increment
</button>
</div>
)
}
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
)
}







