简体   繁体   English

功能组件的哪些部分在重新渲染时运行?

[英]what parts of a functional component gets run on a re-render?

I am used to class components in React, but am trying to learn React hooks.我习惯了 React 中的 class 组件,但我正在尝试学习 React 钩子。 I know that in class components, there is render() method.我知道在 class 组件中,有render()方法。 This method is what is called whenever the class component gets re-rendered.每当重新渲染 class 组件时,都会调用此方法。 However, for a functional component with state (react hooks), there is no such render() method.但是,对于具有 state(react hooks)的功能组件,没有这样的render()方法。 Is the entire function being run on every re-render?整个 function 是否在每次重新渲染时运行? If so, doesn't the state get reset back to the default state value if every line of code of the function is run?如果是这样,如果 function 的每一行代码都运行,state 是否会重置回默认的 state 值? Here is an example snippet — for instance, if this component gets re-rendered when I call setAnimal, doesn't the re-rendering make the animal be reset back to "dog"?这是一个示例片段——例如,如果这个组件在我调用 setAnimal 时被重新渲染,那么重新渲染不会使动物被重置回“狗”吗?

 const SearchParams = () => { const [location, setLocation] = useState("Seattle, WA"); const [animal, setAnimal] = useState("dog"); return ( <div className="search-params"> <form> <label htmlFor="location"> Location <input id="location" value={location} placeholder="Location" onChange={(e) => setLocation(e.target.value)} /> </label> <label htmlFor="animal"> Animal <select id="animal" value={animal} onChange={(e) => setAnimal(e.target.value)} onBlur={(e) => setAnimal(e.target.value)} > <option>All</option> {ANIMALS.map((animal) => ( <option value={animal}>{animal}</option> ))} </select> </label> <button>Submit</button> </form> </div> ); };

The entire function is re-run.重新运行整个 function。 However, the useState() stores the state and does not get overridden.但是,useState() 存储 state 并且不会被覆盖。 When you do useState("SOMETHING") the value you pass is the initial default value and only gets set once (aka on the first initialization of it).当您执行 useState("SOMETHING") 时,您传递的值是初始默认值,并且只设置一次(也就是在它的第一次初始化时)。

React will remember its current value between re-renders, and provide the most recent one to our function. React 会在重新渲染之间记住它的当前值,并将最新的值提供给我们的 function。 - Pulled directly from reactjs.org/docs/hooks-state.html - 直接取自reactjs.org/docs/hooks-state.html

Based on what you asked I hope this answers it!根据你的要求,我希望这能回答它!

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

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