-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
react hooks setState and class setState #7
Comments
例子: function Example() {
const [count, setCounter] = useState(0);
function increment() {
setCounter((count) => count + 1); // 或者: setCounter(count + 1); 自己尝试着两者的区别
}
function handleClick() {
increment();
increment();
increment();
}
return(<button onClick={handleClick}>{count}</button>)
} |
facebook/react#16295 (comment)
|
如果我说
state = {count: 0}
/** class */
setState({count: 1}, () => console.log(this.state.count))
/** hooks */
setState({count: 1})
state = {count: 0, name: ''}
/** class */
setState({count: 1}, () => {
console.log(this.state.count) // {count: 1, name: ''}
})
/** hooks */
setState({count: 1}) // {count: 1}
state = {user: {car: {items: 3}}}
/** class */
state.user.car.items = 5
setState(state, () => {
console.log(this.state.user.car.items) // 5
})
/** hooks */
state.user.car.items = 6
setState(state) // items is 6
const [todos, setTodos] = useState(someTodosArray);
/** un-re-render */
const onClick = () => {
todos[3].completed = true;
setTodos(todos);
}
/** re-render */
const onClick = () => {
const newTodos = todos.slice();
newTodos[3].completed = true;
setTodos(newTodos);
} Blogged Answers: A (Mostly) Complete Guide to React Rendering Behavior |
前两天开代码评审,因为是一个小项目,在其中用到了hooks。有个同事看到了一个事件处理里有两个setState。就提出来了会有性能问题。当时我觉得是没有这个问题的,会有批处理,和class中的setState一样。
相关的解释可以看这两个链接:
Batching update in react-hooks #14259
State updates from useState hook not always collapsed? #14189
因为来自外部的更新,比如
setTimeout
不会进行批量处理,所以最好还是按照dan的建议使用reducer
The text was updated successfully, but these errors were encountered: