react如何定义数据
定义组件内部状态(State)
使用 useState Hook 创建组件内部状态。适用于需要在组件内部维护和更新的数据。
import React, { useState } from 'react';
function ExampleComponent() {
const [count, setCount] = useState(0); // 初始值为0
return (
<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
);
}
定义组件属性(Props)
通过父组件传递数据到子组件,子组件通过 props 接收。适用于父子组件间的数据传递。
function ChildComponent(props) {
return <div>{props.message}</div>;
}
function ParentComponent() {
return <ChildComponent message="Hello from parent!" />;
}
使用Context跨组件共享数据
通过 createContext 和 useContext 实现跨层级组件数据共享。
import React, { createContext, useContext } from 'react';
const DataContext = createContext();
function Parent() {
return (
<DataContext.Provider value={{ key: "Shared Data" }}>
<Child />
</DataContext.Provider>
);
}
function Child() {
const data = useContext(DataContext);
return <div>{data.key}</div>;
}
使用Ref存储可变值
通过 useRef 存储不需要触发渲染的可变值(如DOM引用或定时器ID)。
import React, { useRef } from 'react';
function RefExample() {
const inputRef = useRef(null);
const focusInput = () => inputRef.current.focus();
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
全局状态管理(Redux/Zustand)
通过第三方库(如Redux或Zustand)管理跨组件的全局状态。
Redux示例:
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
const store = createStore((state = { value: 0 }, action) => {
if (action.type === 'increment') return { value: state.value + 1 };
return state;
});
function Counter() {
const value = useSelector(state => state.value);
const dispatch = useDispatch();
return <button onClick={() => dispatch({ type: 'increment' })}>{value}</button>;
}
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
数据持久化(LocalStorage/SessionStorage)
结合 useEffect 和浏览器存储API实现数据持久化。

import { useState, useEffect } from 'react';
function PersistentCounter() {
const [count, setCount] = useState(
() => parseInt(localStorage.getItem('count')) || 0
);
useEffect(() => {
localStorage.setItem('count', count);
}, [count]);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}






