scratch预备知识
自己是个前端小白,最近在做二次开发scratch前端项目,封装出自定义的scratch功能,scratch是使用react前端框架还有redux状态管理器webpack打包的,这个项目很大,所以就想把自己平时学习scratch做一个总结,并分享一下。
-
react 高阶组价(HOC)
高阶组件(HOC)是 React 中用于复用组件逻辑的一种高级技巧。HOC 自身不是 React API 的一部分,它是一种基于 React 的组合特性而形成的设计模式。
具体而言,高阶组件是参数为组件,返回值为新组件的函数。
例如://例如,假设有一个 CommentList 组件,它订阅外部数据源,用以渲染评论列表: class CommentList extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { // 假设 "DataSource" 是个全局范围内的数据源变量 comments: DataSource.getComments() }; } componentDidMount() { // 订阅更改 DataSource.addChangeListener(this.handleChange); } componentWillUnmount() { // 清除订阅 DataSource.removeChangeListener(this.handleChange); } handleChange() { // 当数据源更新时,更新组件状态 this.setState({ comments: DataSource.getComments() }); } render() { return ( <div> {this.state.comments.map((comment) => ( <Comment comment={comment} key={comment.id} /> ))} </div> ); } } //使用HOC const CommentListWithSubscription = withSubscription( CommentList, (DataSource) => DataSource.getComments() );
这样使用封装的withSubscription函数可以返回一个将数据源提出来的组件。可以通过withSubscription函数注入不同的数据源来渲染不同的组件。
withSubscription的封装源码:// 此函数接收一个组件... function withSubscription(WrappedComponent, selectData) { // ...并返回另一个组件... return class extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { data: selectData(DataSource, props) }; } componentDidMount() { // ...负责订阅相关的操作... DataSource.addChangeListener(this.handleChange); } componentWillUnmount() { DataSource.removeChangeListener(this.handleChange); } handleChange() { this.setState({ data: selectData(DataSource, this.props) }); } render() { // ... 并使用新数据渲染被包装的组件! // 请注意,我们可能还会传递其他属性 return <WrappedComponent data={this.state.data} {...this.props} />; } }; }
-
React-Redux
React-Redux 将所有组件分成两大类:UI 组件(presentational component)和容器组件(container component);你观察scratch的文件夹架构
-
connect()
import { connect } from 'react-redux' const VisibleTodoList = connect()(TodoList);
上面VisibleTodoList 便是通过UI组件TodoList,通过connect方法自动生成的容器组件。
import { connect } from 'react-redux' const VisibleTodoList = connect( mapStateToProps, mapDispatchToProps )(TodoList)
connect方法接受两个参数:mapStateToProps和mapDispatchToProps。它们定义了 UI 组件的业务逻辑。前者负责输入逻辑,即将state映射到 UI 组件的参数(props),后者负责输出逻辑,即将用户对 UI 组件的操作映射成 Action。
-
mapStateToProps()
它是一个函数,建立一个从(外部的)state对象到(UI 组件的)props对象的映射关系。
mapStateToProps执行后应该返回一个对象,里面的每一个键值对就是一个映射。const mapStateToProps = state => { return { todos: state.todos } }
-
mapDispatchToProps()
mapDispatchToProps是connect函数的第二个参数,用来建立 UI 组件的参数到store.dispatch方法的映射。它定义了哪些用户的操作应该当作 Action,传给 Store。它可以是一个函数,也可以是一个对象。
const mapDispatchToProps = ( dispatch, ownProps //ownProps(容器组件的props对象) ) => { return { onClick: () => { dispatch({ type: 'SET_VISIBILITY_FILTER', filter: ownProps.filter }); } }; }
-
这是scratch项目两个关键的知识点,下一篇写一下目录结构和用到的一些包