2017-08-16 66 views
3

該組件的渲染方法確實使用了提供給組件的任何道具。當涉及到調用渲染方法時,ReactJS是否「聰明」?

當道具改變時,組件是否會重新渲染?

class MyComponent extends React.Component { 
    constructor(props) { 
    super(props); 
    const { propValue } = props; 
    // do something with propValue... 
    } 
    render() { 
    return (
     <div>foo</div> 
    ); 
    } 
} 
+2

[相關(http://lucybain.com/blog/2017/react-js-when-to-rerender/) 。 – PeterMader

回答

2

是的,除非您執行shouldComponentUpdate,否則組件將重新呈現。您可以繼承PureComponent,它使用propstate的淺比較以及以前的值來確定組件是否應更新。

+0

@Chris謝謝你指出這一點。我會更新我的答案。 – Marko

2

將會調用render - 是的。除非你執行shouldComponentUpdate返回false

DOM將被重新渲染 - 沒有。

另外,您也可以看看https://babeljs.io/docs/plugins/transform-react-constant-elements/,它提升靜態元素。

const Hr =() => { 
    return <hr className="hr" />; 
}; 

缺貨

const _ref = <hr className="hr" />; 

const Hr =() => { 
    return _ref; 
};