与其在类中编写组件,不如使用函数语法。
如何覆盖componentDidMount,componentWillMount内部功能部件? 可能吗
componentDidMount
componentWillMount
const grid = (props) => { console.log(props); let {skuRules} = props; const componentDidMount = () => { if(!props.fetched) { props.fetchRules(); } console.log('mount it!'); }; 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> ) }
编辑: 通过引入,Hooks可以实现生命周期的行为以及功能组件中的状态。目前
Hooks
挂钩是一项新的功能建议,使您无需编写类即可使用状态和其他React功能。它们作为 v16.8.0* 的一部分在React中发布 *
useEffect钩子可用于复制生命周期行为,useState并可用于将状态存储在功能组件中。
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:
componentWillUnmount
例如:componentWillUnmount
useEffect(() => { window.addEventListener('unhandledRejection', handler); return () => { window.removeEventListener('unhandledRejection', handler); } }, [])
要以useEffect特定事件为条件,可以为其提供一系列值以检查更改:
例如: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
如果包含此数组,请确保包含组件范围中随时间变化的所有值(属性,状态),否则最终可能引用以前的渲染中的值。
使用有一些细微的地方useEffect; 查看API Here。
Here
v16.7.0之前
函数组件的属性是它们无权访问Reacts生命周期函数或this关键字。React.Component如果要使用生命周期函数,则需要扩展该类。
this
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> ) } }
当您只需要呈现组件而不需要额外的逻辑时,功能组件就很有用。