Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

react 函数组件里面自定义组件用标签的形式去渲染,为什么会导致重复渲染

函数式编写页面,其中有ChildRender这个自定义组件,ChildRender放置在整个大的App函数组件里面,组件使用方式是以标签的形式使用<ChildRender/>;但如果这样写的话,我发现每次useState时整个ChildRender组件都会被重新挂载渲染。除非使用useCallback把ChildRender组件包裹一层后,ChildRender才不会重新挂载渲染
image.png

import React,{useState,useCallback} from 'react'
// import ChildRender from './componment/child'


const App = () => {
    const ChildRender = () =>{
        return (
            <div style={{width:'100px',height:'100px',background:'red'}}>
                <div>这是子组件11111</div>
                <img style={{width:'30px',height:'30px'}} src={require('./1.jpg')}/>
            </div>
        )
    }
    const [count,setCount] = useState(0,)
  
    return(
        <div>
            <div>
                <span>this is my app</span>
                <span>{count}</span>
                <button onClick={()=>setCount(count +1)}>点我</button>
            </div>
            <ChildRender/> 
            {/* {ChildRender()} 用函数调用的方式不会重新挂载渲染节点*/} 
        </div>
    )
}

export default App

但非常奇怪的是,如果我不用标签的形式去渲染,而是用函数调用的方式渲染,或者我把整个ChildRender组件放置到App组件之上,或者改用class写法,节点并不会重新挂载渲染,这让我有点迷惑,希望有人能回答一下


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

image.png
image.png
不知提问者是以何种方式判断“节点是否渲染”,实际上无论是使用函数调用的形式或者使用标签的形式,ChildRender都会被重新调用,而react判断是否需要重新挂载节点是根据fiber的diff算法。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...