在反应教程中:
https://egghead.io/lessons/javascript-redux-react-todo-list-example-filtering-todos
有扩展的主要组件创建:
class TodoApp extends Component {
render() {
const visibleTodos = getVisibleTodos(
this.props.todos,
this.props.visibilityFilter
);
.
. // Input and Button stuff
.
而另一个组件只是创建一个包含函数的const:
const FilterLink = ({
filter,
children
}) => {
return (
<a href='#'
onClick={e => {
e.preventDefault();
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter
});
}}
>
{children}
</a>
)
}
我看到的差异,首先用类创建一个渲染函数,另一个用于发送回模板的返回函数 .
有什么区别?我听说将来只允许使用扩展组件?
2 回答
见:React.createClass vs. ES6 arrow function
简短的回答是,您希望尽可能多地使用无状态功能组件(SFC);您的大多数组件应该是SFC .
在以下情况下使用传统的
Component
类:你需要当地的州(
this.setState
)你需要一个生命周期钩子(
componentWillMount
,componentDidUpdate
等)您需要通过refs访问后备实例(例如
<div ref={elem => this.elem = elem}>
)class Foo扩展了Component {},结果包含一些React生命周期钩子,而const Foo =(props)=> {}则没有 . 因此,后者应该产生更高性能的代码,并且将被视为“无状态”或“纯粹”组件,因为它不带任何额外的 Baggage .