简体   繁体   English

用无状态组件反应备忘录

[英]React memo with stateless component

Before react introduce memo and hook All functional component was stateless.在 react 引入memohook之前,所有功能组件都是无状态的。

After Introducing memo and hook I'm little confused with these two concept.在介绍了memohook之后,我对这两个概念有点困惑。

Is React.memo for functions that use hook only ? React.memo是否适用于使用钩子的函数?

Should I update all my stateless functional component to React.memo for optimizing?我应该将我所有的无状态功能组件更新React.memo以进行优化吗? Or react optimize it when a function does not use hook automatically?或者当 function 不自动使用钩子时对其进行优化?

For understanding what React.memo is used for, first you have to understand the difference between React.Component and React.PureComponent .要了解React.memo的用途,首先您必须了解React.ComponentReact.PureComponent之间的区别。

From the docs -从文档 -

The difference between them is that React.Component doesn't implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.它们之间的区别在于,React.Component 没有实现 shouldComponentUpdate(),但 React.PureComponent 用浅 prop 和 state 比较来实现它。

If your React component's render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.如果你的 React 组件的 render() function 在给定相同的 props 和 state 的情况下呈现相同的结果,你可以在某些情况下使用 React.PureComponent 来提高性能。

React.memo is the same as a React.PureComponent , just for the functional components. React.memoReact.PureComponent相同,只是针对功能组件。 So, if you think that with a given props, your component will be rendered the same, you can wrap your component with React.memo for performance boost and memoizing the result as mentioned in the docs .因此,如果您认为使用给定的道具,您的组件将呈现相同的效果,您可以使用React.memo包装您的组件以提高性能并记忆文档中提到的结果。

But do specifically take a look at the line in the docs, which says -但是请特别看一下文档中的那一行,上面写着 -

This method only exists as a performance optimization.此方法仅作为性能优化存在。 Do not rely on it to “prevent” a render, as this can lead to bugs.不要依赖它来“阻止”渲染,因为这可能会导致错误。

And you should make your decision about using React.memo irrespective of the hooks .而且你应该做出关于使用React.memo的决定,而不考虑hooks

React.memo is equivalent to shouldComponentUpdate and PureComponent for functional components. React.memo相当于功能组件的shouldComponentUpdatePureComponent It performs a shallow comparison between current and next props and doesn't have anything to do with local state introduced by hooks .它在当前和下一个props之间进行浅层比较,与hooks引入的本地 state 没有任何关系。 You still use it to prevent useless renders by comparing props to determine if they changed or not:您仍然使用它来通过比较道具以确定它们是否更改来防止无用的渲染:

const Component = props =>{
    //even with memo changes in local state still trigger a new render
    const [state, setState] = useState({foo: 'foo'})
}

export default React.memo(Component) //Won't rerender unless props changes

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

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