【发布时间】:2019-11-21 18:14:53
【问题描述】:
我正在尝试从基于类的组件迁移到功能组件。它是一个使用mapState 的连接组件。
这就是我所拥有的:
import { connect } from 'react-redux'
import { fetchArticles } from '../shared/actions/articleActions';
import { AppState } from '../shared/types/genericTypes';
import Article from '../shared/models/Article.model';
type Props = {
articles?: Article[]
fetchArticles?: any,
};
const mapState = (state: AppState, props) => ({
articles: state.articleReducers.articles,
...props
});
const actionCreators = {
fetchArticles,
};
class NewsArticles extends Component<Props> {
componentDidMount() {
if (!this.props.articles || !this.props.articles.length) {
this.props.fetchArticles();
}
}
render() {
return (...);
}
}
export default connect(mapState, actionCreators)(NewsArticles)
这是我现在拥有的:
// same imports except for FC and useEffec from react.
type Props = {
articles?: Article[];
fetchArticles?: any;
};
const mapState = (state: AppState, props: Props) => ({
articles: state.articleReducers.articles,
...props,
});
const actionCreators = {
fetchArticles,
};
const NewsArticles: FC<Props> = ({ articles, fetchArticles }) => {
useEffect(() => {
if (!articles || !articles.length) {
fetchArticles();
}
}, []);
return (...);
};
export default connect(mapState, actionCreators)(NewsArticles);
我最关心的是道具。
以前他们是这样的
const mapState = (state: AppState, props) => ({
articles: state.articleReducers.articles,
...props
});
并像这样使用:
componentDidMount() {
if (!this.props.articles || !this.props.articles.length) {
this.props.fetchArticles();
}
}
现在我有了一个功能组件,我得到了这个
const mapState = (state: AppState, props: Props) => ({
articles: state.articleReducers.articles,
...props,
});
并像这样使用:
useEffect(() => {
if (!articles || !articles.length) {
fetchArticles();
}
}, []);
那么props 将如何工作现在articles 和fetchArticles 不像this.props.articles 和只有articles 那样被调用所以,在mapState 上传播道具…props 是否有意义?
【问题讨论】:
-
是的,您所做的绝对正确,props 中的内容不取决于组件是类还是功能性。它由连接 HOC 提供
-
mapState 调用中的道具当然是组件自己的道具,所以如果你想将它可能收到的任何其他道具分配给它的状态,那么在地图调用中传播它们是有意义的。但是除非你对 props 执行某种操作,而且通常即使你这样做了,从它们派生状态通常是不必要的。因此,无论组件类型如何,它都不是必需的,但它没有真正的缺点。
-
无需传播
props。NewsArticles需要的所有道具都由connect提供:articlesfromstateandfetchArticlesfromactionCreators
标签: javascript reactjs typescript ecmascript-6 redux