react 如何更新 view
更新视图的基本方法
在 React 中,视图更新通常通过状态(state)或属性(props)的变化触发。组件的状态变化会自动触发重新渲染。
使用 useState Hook 管理状态:
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>
);
}
使用 useEffect 处理副作用
当需要响应 props 或 state 变化执行副作用时,使用 useEffect Hook:

import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(response => response.json())
.then(data => setUser(data));
}, [userId]); // 依赖数组确保只在 userId 变化时重新获取
return <div>{user ? user.name : 'Loading...'}</div>;
}
性能优化技术
对于复杂组件,可使用 React.memo 避免不必要的重新渲染:
const MemoizedComponent = React.memo(function MyComponent({ prop }) {
return <div>{prop}</div>;
});
使用 useCallback 和 useMemo 缓存函数和计算结果:

const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
类组件更新方式
在类组件中,使用 this.setState() 触发更新:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState({ seconds: this.state.seconds + 1 });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div>Seconds: {this.state.seconds}</div>;
}
}
强制更新方法
极少数情况下可能需要强制更新,可使用 forceUpdate(不推荐常规使用):
this.forceUpdate();
在函数组件中,可以通过改变状态值来达到类似效果:
const [_, forceUpdate] = useState(0);
forceUpdate(c => c + 1);






