react如何修改值
修改 React 中的值
在 React 中修改值通常涉及状态管理,根据不同的场景可以选择以下方法:
使用 useState Hook(函数组件)
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
使用 useReducer Hook(复杂状态逻辑)
import React, { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
throw new Error();
}
}
function Example() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
</div>
);
}
使用类组件中的 setState
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
直接修改 DOM 元素的值(不推荐,仅特定场景使用)

function Example() {
const handleChange = (e) => {
console.log(e.target.value);
};
return <input type="text" onChange={handleChange} />;
}
注意事项
- 避免直接修改状态对象,例如
this.state.count = 1,这种方式不会触发重新渲染。 - 对于数组或对象的更新,确保使用不可变方式,例如使用扩展运算符或
concat方法。 - 在函数组件中,状态更新是异步的,连续调用
setState可能会合并。






