- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑下面的钩子(Hook)示例
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
基本上,我们使用 this.forceUpdate() 方法强制组件在 React 类组件中立即重新渲染,如下例所示
class Test extends Component{
constructor(props){
super(props);
this.state = {
count:0,
count2: 100
}
this.setCount = this.setCount.bind(this);//how can I do this with hooks in functional component
}
setCount(){
let count = this.state.count;
count = count+1;
let count2 = this.state.count2;
count2 = count2+1;
this.setState({count});
this.forceUpdate();
//before below setState the component will re-render immediately when this.forceUpdate() is called
this.setState({count2: count
}
render(){
return (<div>
<span>Count: {this.state.count}></span>.
<button onClick={this.setCount}></button>
</div>
}
}
但是我的疑问是如何强制上述功能组件立即使用钩子(Hook)重新渲染?
最佳答案
这可以通过 useState
或 useReducer
实现,因为 useState
uses useReducer
internally :
const [, updateState] = React.useState();
const forceUpdate = React.useCallback(() => updateState({}), []);
forceUpdate
不适合在正常情况下使用,仅在测试或其他 Unresolved 情况下使用。这种情况可以通过更传统的方式来解决。
setCount
是错误使用 forceUpdate
的示例,出于性能原因,setState
是异步的,不应仅仅因为它而强制同步状态更新未正确执行。如果状态依赖于先前设置的状态,则应使用 updater function 来完成,
If you need to set the state based on the previous state, read about the updater argument below.
<...>
Both state and props received by the updater function are guaranteedto be up-to-date. The output of the updater is shallowly merged withstate.
setCount
可能不是一个说明性示例,因为其目的尚不清楚,但更新程序函数就是这种情况:
setCount(){
this.setState(({count}) => ({ count: count + 1 }));
this.setState(({count2}) => ({ count2: count + 1 }));
this.setState(({count}) => ({ count2: count + 1 }));
}
这被 1:1 转换为钩子(Hook),但用作回调的函数应该更好地被记住:
const [state, setState] = useState({ count: 0, count2: 100 });
const setCount = useCallback(() => {
setState(({count}) => ({ count: count + 1 }));
setState(({count2}) => ({ count2: count + 1 }));
setState(({count}) => ({ count2: count + 1 }));
}, []);
关于javascript - 如何在 React 中使用 hooks 强制组件重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53215285/
我是一名优秀的程序员,十分优秀!