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

Categories

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

javascript - 当没有新的道具出现时,为什么我的标头组件会重新呈现?(Why is my header component rerendering when no new props are coming…?)

https://codesandbox.io/s/crimson-field-83hx6(https://codesandbox.io/s/crimson-field-83hx6)

I have a Header component that returns a fixed text with a console.log(我有一个Header组件,它使用console.log返回固定文本) const Header = props => { console.log("header render"); return ( <header> <h1>header</h1> </header> ); }; Within my parent component, I have a function called changeTab that changes the tab and sets it into the state:(在我的父组件中,我有一个名为changeTab的函数,该函数更改选项卡并将其设置为状态:) class App extends Component { state = { tabs: { selectedTab: "" } }; changeTab(name) { let tabs = { ...this.state.tabs }; tabs.selectedTab = name; this.setState({ tabs }); } render() { return ( <div> <Header /> <button onClick={() => this.changeTab()}>change tab</button> </div> ); } } When I click on the button to change the tab, the console.log from the header fires.(当我单击按钮以更改选项卡时,将触发标题中的console.log 。) Why is this happening?(为什么会这样呢?) No new props are being passed to Header and also Header isnt reliant on state.(没有新的道具传递给Header,并且Header不依赖于状态。)   ask by Syn translate from so

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

1 Reply

0 votes
by (71.8m points)

The reason why your Header component is being rendered again after running the changeTab function is because you're calling the setState function of a React.Component .(运行changeTab函数后再次渲染Header组件的原因是因为您正在调用React.ComponentsetState函数。)

This function runs a re-render of the component it's calling on and all its children.(此函数对正在调用的组件及其所有子组件进行重新渲染。) A quote from the documentation :(来自文档的报价:) setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state.(setState()使更改进入组件状态并告诉React该组件及其子级需要使用更新后的状态重新呈现。) This is the primary method you use to update the user interface in response to event handlers and server responses.(这是用于响应事件处理程序和服务器响应而更新用户界面的主要方法。) Your Header component has nothing to do with the state of the parent component.(您的Header组件与父组件的状态无关。) But it's re-rendered because it's the child of the parent component.(但这是因为它是父组件的子组件而被重新渲染。) If you don't want your Header component to be re-rendered upon clicking the changeTab function, you should consider to move the logic of your tabs to a different component, or moving the Header component up the dom-tree (if possible).(如果您不希望在单击changeTab函数时重新呈现Header组件,则应考虑将选项卡的逻辑移动到其他组件,或者将Header组件移到dom-tree上(如果可能)。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...