如何在特定时间间隔内强制在 React Native 中进行深度渲染?
How to force a deep render in React Native on a specific interval?
如何每半秒更新一次 React 组件?我需要更新组件以显示从 api 流入的新信息。我希望组件重新呈现,以便它可以在特定时间间隔显示新信息。
在 React 中,我们可以使用 forceUpdate
。不幸的是,在 React Native 中,我们没有那么奢侈。幸运的是,每次调用 setState
函数时,useState
都会提供深度渲染。这个解决方案有点老套,但它完成了工作。运作方式如下:
const [inProgress, setInProgress] = useState(false); //This should be true when you want rerendering to happen.
const [updateCounter, setUpdateCounter] = useState(0); //This is the state the will force the update.
if (inProgress) {
setTimeout(() => setUpdateCounter(updateCounter + 1), 500);
}
这是我发现的最简单的方法。本例中的间隔设置为 500 毫秒。但是,它可以设置为任何你想要的。我选择半秒是因为我觉得它为用户提供了足够的响应感觉,同时也为 setState
到 运行 提供了足够的时间。
如何每半秒更新一次 React 组件?我需要更新组件以显示从 api 流入的新信息。我希望组件重新呈现,以便它可以在特定时间间隔显示新信息。
在 React 中,我们可以使用 forceUpdate
。不幸的是,在 React Native 中,我们没有那么奢侈。幸运的是,每次调用 setState
函数时,useState
都会提供深度渲染。这个解决方案有点老套,但它完成了工作。运作方式如下:
const [inProgress, setInProgress] = useState(false); //This should be true when you want rerendering to happen.
const [updateCounter, setUpdateCounter] = useState(0); //This is the state the will force the update.
if (inProgress) {
setTimeout(() => setUpdateCounter(updateCounter + 1), 500);
}
这是我发现的最简单的方法。本例中的间隔设置为 500 毫秒。但是,它可以设置为任何你想要的。我选择半秒是因为我觉得它为用户提供了足够的响应感觉,同时也为 setState
到 运行 提供了足够的时间。