小总结

2 篇文章 0 订阅

function组件vsclass组件

类型检查

/**
* class组件
*/
import PropTypes from 'prop-types';

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

// 指定 props 的默认值:
Greeting.defaultProps = {
  name: 'Stranger'
};

Greeting.propTypes = {
  name: PropTypes.string
};


//=================在 React 组件类中声明 defaultProps 作为静态属性=========================//

class Greeting extends React.Component {
  static defaultProps = {
    name: 'stranger'
  }

  render() {
    return (
      <div>Hello, {this.props.name}</div>
    )
  }
}
/**
* 函数组件
*/
import PropTypes from 'prop-types'

function HelloWorldComponent({ name }) {
  return (
    <div>Hello, {name}</div>
  )
}

HelloWorldComponent.propTypes = {
  name: PropTypes.string
}

export default HelloWorldComponent

react-router

  • class组件 修饰器写法
import { withRouter } from 'react-router-dom';

@withRouter
export default class BreadCrumb extends PureComponent {
    
  handleClick=()=>{
      this.props.history.replace(`/setting/hroa/saasRole/${res.data}`);
  }

  render() {
    return (
    );
  }
}


export default withRouter(LoginRedirect);
  • function hook写法
import { useLocation, useHistory } from 'react-router-dom';

function Index() {
  const history = useHistory();
  const location = useLocation();
  const [queryParams, setQueryParams] = useState(qs.parse(location.search));
    
  function handleClick(){
      history.push({
        search: qs.stringify(queryParams),
      });
  }

  return (
  );
}

redux

  • class 装饰器
@connect(saasRoleSelector)
class SaaSRoleDetailContent extends React.Component {
    
  handleConfirm = () => {
    const { dispatch } = this.props;
    dispatch(actionGetArmPositionList({ companyId: user.companyId }));
  }

  render() {
    );
  }
}

SaaSRoleDetailContent.defaultProps = {
  dispatch() {},
  saasRoleInfo: {},
};

SaaSRoleDetailContent.propTypes = {
  dispatch: PropTypes.func,
  saasRoleInfo: PropTypes.shape({}),
};
  • function hooks
import { useSelector, useDispatch } from 'react-redux';

function Index() {
  const dispatch = useDispatch();
  const okr = useSelector((state) => state.okr);
  const user = useSelector((state) => state.user);
 
  // 刷新用户信息
  const onReload = () => {
    dispatch(getUserInfo(userId));
  };
    
  useEffect(() => {
    dispatch(getPeriods());
  }, []);

  return (
  );
}

createSelector

import { createSelector } from 'reselect'

const shopItemsSelector = state => state.shop.items
const taxPercentSelector = state => state.shop.taxPercent

//只有在某个参数发生变化的时候才发生计算过程.
const taxSelector = createSelector(
  subtotalSelector,
  taxPercentSelector,
  (subtotal, taxPercent) => subtotal * (taxPercent / 100)
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值