function组件vs
class组件
类型检查
-
function组件和class组件都可以用
PropTypes
进行类型检查同样用于
React.memo
/React.forwardRef
创建的组件
/**
* 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)
)