Edit:随着Hooks
的引入,可以实现生命周期类型的行为以及功能组件中的状态.目前
钩子是一个新的特性建议,允许您使用状态和其他
useEffect
钩子可用于复制生命周期行为,useState
钩子可用于在功能组件中存储状态.
基本语法:
useEffect(callbackFunction, [dependentProps]) => cleanupFunction
您可以在钩子中实现您的用例,比如
const grid = (props) => {
console.log(props);
let {skuRules} = props;
useEffect(() => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
}, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
useEffect
还可以返回一个函数,该函数将在卸载组件时运行.这可以用来取消对听众的订阅,复制componentWillUnmount
的行为:
Eg: componentWillUnmount
useEffect(() => {
window.addEventListener('unhandledRejection', handler);
return () => {
window.removeEventListener('unhandledRejection', handler);
}
}, [])
要使useEffect
以特定事件为条件,可以为其提供一个值数组以判断更改:
Eg: componentDidUpdate
componentDidUpdate(prevProps, prevState) {
const { counter } = this.props;
if (this.props.counter !== prevState.counter) {
// some action here
}
}
挂钩当量
useEffect(() => {
// action here
}, [props.counter]); // checks for changes in the values in this array
如果包含此数组,请确保包含组件范围中随时间变化的所有值(props 、状态),否则最终可能会引用以前渲染中的值.
使用useEffect
有一些微妙之处;查看API Here
.
Before v16.7.0
功能组件的特性是它们无权访问Reacts生命周期功能或this
关键字.如果想使用lifecycle函数,需要扩展React.Component
类.
class Grid extends React.Component {
constructor(props) {
super(props)
}
componentDidMount () {
if(!this.props.fetched) {
this.props.fetchRules();
}
console.log('mount it!');
}
render() {
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
}
当您只想渲染组件而不需要额外的逻辑时,函数组件非常有用.