边副作用
一句话解释
边副作用是 任何操作那个 affects 某事之外组件 — 数据获取, DOM manipulation, subscriptions, logging.
用大白话说
In React, a pure component is one that, given the same props and state, always returns the same JSX and doesn't affect anything else. A side effect is anything that breaks this purity — fetching data, writing to localStorage, subscribing to a websocket, manually changing the DOM, logging to the console.
React components should be pure (just compute JSX from props/state). Side effects are handled separately, in useEffect. This separation keeps rendering predictable: React can call your component function any number of times (for reconciliation, concurrent rendering) without worrying about side effects firing unexpectedly.
The useEffect Hook is the designated place for side effects. It runs after render, so the component's pure render logic is decoupled from impure effects.
示例
// Pure: just returns JSX from props
function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
// Side effect: fetches data after render
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(setUser);
}, [userId]);
return user ? <h1>{user.name}</h1> : <Spinner />;
}获取是 边副作用 — 它 reaches 之外组件. useEffect 运行它 之后渲染, keeping 渲染 pure.
相关术语
相关资源
相关课程
- useEffect
学习边 副作用 and useEffect.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。