Yang03 / blog

0 stars 0 forks source link

Functional stateless , pure, dumb components #18

Open Yang03 opened 7 years ago

Yang03 commented 7 years ago

PureComponent

React.PureComponent 和 React.Component 完全一样,但是它实现了 shouldComponentUpdate()的 prop 和 state的浅比较

如果React component's render() function 在相同prop 和 state下呈现相同的结果,你可以使用 React.PureComponent 来提高性能。

注:React.PureComponent的shouldComponentUpdate()只是浅比较,如果是复杂数据结构,它可能会返回false在需要深层比较的情况下,只有在prop 和 state比较简单的情况下才能extends PureComponent, 或者使用forceUpdate()在你知道深层的数据结构已经改变, 或者使用immutable数据 来更快的做深比较 此外,React.PureComponent 的shouldComponentUpdate() 将跳过所有子组件的更新,确保所有的子组件是“pure”

Functional stateless components

函数式定义,由于无状态组件没有内部状态,输出的内容取决于作为函数输入的prop

    const Helloworld = ({name}) => {
        const sayHi = (event) => {
            console.log('sayhi')     
        }
        return (
                <p onClick={sayHi}>{name}</p>
            )
    }

Dumb component

diff pureComponent and Function Stateless components

diff functional and Dumb

diff PureComponent and Dumb

Yang03 commented 7 years ago

https://stackoverflow.com/questions/40703675/react-functional-stateless-component-purecomponent-component-what-are-the-dif

https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0

Yang03 commented 7 years ago

presentational components

container components

Benefits of This Approach

container components没有 DOM。他只需要提供组合不同 UI 所需要的边界

何时使用容器?

我猜测你开始构建你的 app 时首先创建的是表现层组件。最后你会意识到传递了太多 props 到中间组件。当你注意到一些组件不需要用到他们接收到的 props ,只是要转发他们下去并且你重写了所有这些中间组件他们的子组件需要的更多数据,那是使用一些容器组件的好时间。通过这种方式你可以获取数据和行为 props 给叶组件而不需要麻烦树结构中间无关的组件。

表现层组件和容器组件都可以分为这些两种种类。以我的经验,表现层容器倾向于无状态纯函数,容器倾向于有状态纯类。但这不是规则但根据观察,且我已经发现在特定的情况下会出现完全相反的情况。