简体   繁体   English

React 避免重新渲染 useState

[英]React avoid re render useState

I have a component which uses react-native-scrollable-tabview .我有一个使用react-native-scrollable-tabview I'm having a problem though.不过我有问题。

The component has 2 props: page and initialPage .该组件有 2 个道具: pageinitialPage

When rendering the component for the first time, I should set initialPage , otherwise it doesn't work.第一次渲染组件时,我应该设置initialPage ,否则它不起作用。

However when rendering the component again, if I change this initialPage it goes the new page (tab) but it doesn't render it.但是,当再次渲染组件时,如果我更改此initialPage它会转到新页面(选项卡),但不会渲染它。 BUT, if I set the page then it works.但是,如果我设置了page那么它就可以工作了。

So the idea is:所以这个想法是:

First render?先渲染? Set page to undefined and initialPage to N. Subsequent renders?page设置为 undefined 并将initialPage为 N。后续渲染? Set page to N and initialPage to undefined.page设置为 N 并将initialPage为 undefined。

I tried using a flag state variable like this:我尝试使用这样的标志状态变量:

const [firstRender, setFirstRender] = useState(true);

let page = n;
let initialPage = n;

if(first){
   page = undefined;
   setFirstRender(false);
}else{
  initialPage = undefined;
}

Thing is, the setFirstRender triggers a re render so it doesn't work.事实是, setFirstRender会触发重新渲染,因此它不起作用。 However when I go to another screen (using react navigation) and I come back then it works fine.但是,当我转到另一个屏幕(使用反应导航)并返回时,它可以正常工作。

Is there any way to update this firstRender without it triggering a re render?有没有办法更新这个firstRender而不触发重新渲染?

Not sure if this is what you're looking for, but maybe something with useEffect could help?不确定这是否是您要找的东西,但也许useEffect有帮助?

useEffect(() => {
  setFirstRender(false);
}, []);

The array at the end is a dependency and tells the function to only run once, you could also add a value in there that runs only when that value changes as well.最后的数组是一个依赖项,它告诉函数只运行一次,您也可以在其中添加一个仅在该值更改时运行的值。

It appears you aren't checking the value of your state anywhere.看来您没有在任何地方检查您的状态的值。

eg this conditional:例如这个条件:

if(first){
   page = undefined;
   setFirstRender(false);
}else{
  initialPage = undefined;
}

should be changed to rely on the value of state, which you declare as: (const [firstRender, setFirstRender] = useState(true);)应该更改为依赖状态的值,您声明为: (const [firstRender, setFirstRender] = useState(true);)

so所以

if(firstRender){
   page = undefined;
   setFirstRender(false);
}else{
  initialPage = undefined;
}

Additionally, you will probably need to move this conditional into a useEffect where it will update only after the first initial page render.此外,您可能需要将此条件移动到 useEffect 中,它只会在第一次初始页面呈现后更新。

useEffect(() => {
if (firstRender) {
setFirstRender(false) ...etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM