The beauty of React components is that they automagically render and update based on a change in state or props; simply update the state from any place and suddenly your UI element updates -- awesome! There may be a case, however, where you simply want to brute force a fresh render of a React component.
React组件的优点是它们根据state或props的变化自动渲染和更新; 只需从任何地方更新状态,然后您的UI元素就会突然更新-太棒了! 但是,在某些情况下,您可能只想蛮力地对React组件进行新的渲染。
Note: In most cases you should never force a React component to re-render; re-rendering should always be done based on state or props changes. Nonetheless, I don't judge and there may be a case where you legitimately need to force a React component to re-render so let's have it!
注意:在大多数情况下,您永远不要强迫React组件重新渲染。 重新渲染应始终根据状态或道具更改进行。 但是,我没有判断,在某些情况下,您可能确实需要强制React组件重新渲染,所以让我们拥有它!
There are multiple ways to force a React component render but they are essentially the same. The first is using this.forceUpdate(), which skips shouldComponentUpdate:
强制React组件渲染的方法有多种,但本质上是相同的。 第一种是使用this.forceUpdate() ,它会跳过shouldComponentUpdate :
someMethod() { // Force a render without state change... this.forceUpdate(); }Assuming your component has a state, you could also call the following:
假设您的组件处于state ,您还可以调用以下命令:
someMethod() { // Force a render with a simulated state change this.setState({ state: this.state }); }This blog doesn't aim to be prescriptive, so I wont scold developers for using this brute force method. Again, there's likely a better, more "React-y" way to render a component properly, but if you are desperate to get a component render on command, there are many ways to do so with React.
这个博客的目的不是要说明性的,所以我不会责骂使用这种蛮力方法的开发人员。 同样,可能存在更好的,更“ React-y”的方法来正确地渲染组件,但是如果您迫切希望通过命令来渲染组件,则有许多方法可以使用React来实现。
翻译自: https://davidwalsh.name/react-force-render