connect实现原理

版权声明:如果觉的本文好的话,点个赞,您的鼓励是我最大的动力。 https://blog.csdn.net/boysky0015/article/details/88832325
const App= connect(
	mapStateToProps,
	mapDispatchToProps,
)(Index)

这种写法大家很常见吧!
redux中常用的高阶组件(HOC)是connect,想必用过redux都知道。
如果让大家实现一个connect方法,该如何实现呢?

let state = {
	name: 'tianxia',
	age: 18,
	list: [1,3,5,7,9],
}
function connect(fn1) {
	let obj = fn1(state);
	return function(Com) {
		return class Title extends Component {
			render() {
				return <Com {...obj} />
			}
		}
	}
}
class Son extends Component {
	render() {
		return (
			<div>Hello,{ this.props.name }</div>
		)
	}
}
const App = connect((state)=>{
	return {
		name: state.name,
	}
})(Son)

猜你喜欢

转载自blog.csdn.net/boysky0015/article/details/88832325