
图片
如果只想在 state
更改时重新计算某些数据,比如搜索框案例。
vue
1 | <template> |
react
1 | import React, { PureComponent } from 'react'; |
如果你想在 prop
更改时“重置”某些 state
,比如随机默认值案例
vue
Vue提供了一种更通用的方式来观察和响应Vue实例上的数据变动:侦听属性 watch
。
1 | <template> |
react
React生命周期 getDerivedStateFromProps
会在调用 render
方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state
,如果返回 null
则不更新任何内容。
父组件重新渲染时触发,请注意,不管原因是什么,都会在每次渲染前触发此方法。
1 | class Example extends Component { |
改进
直接复制 prop
到 state
是一个非常糟糕的想法。这两者的关键在于,任何数据,都要保证只有一个数据来源,而且避免直接复制它。
vue
1 | <template> |
1 | <template> |
react
1 | function Example (props) { |
1 | class App extends React.Component { |