[Recompose] Flatten a Prop using Recompose
2024-08-30 04:38:05
Learn how to use the ‘flattenProp’ higher order component to take a single object prop and spread each of its fields out as a prop.
For example,we have a 'redux-react' like app:
import React from 'react';
import { withProps } from 'recompose'; // Mock Configuration
function ReactRedux() {
const state = {
name: 'Joe',
status: 'active'
};
return {
connect: (map) => withProps(map(state))
};
} const {connect} = ReactRedux(); const UserStyle = {
position: 'relative',
background: 'lightblue',
display: 'inline-block',
padding: '10px',
cursor: 'pointer',
marginTop: '50px'
}; const mapStateToProps = (state) => ({
name: state.name,
status: state.status
}); let User4 = ({ status, name }) => (
<div style={UserStyle}>
{name} - {status}
</div>
); User4 = connect(mapStateToProps)(User4); export default User4;
Here we using 'connect' & 'mapStateToProps'. 'connect' is also a HoC.
import React from 'react';
import { withProps, compose, flattenProp } from 'recompose'; // Mock Configuration
function ReactRedux() {
const state = {
user: {
name: 'Joo',
status: 'inactive'
},
address: {
street: 'SF',
postcode: ''
}
};
return {
connect: (map) => withProps(map(state))
};
} const {connect} = ReactRedux(); const UserStyle = {
position: 'relative',
background: 'lightblue',
display: 'inline-block',
padding: '10px',
cursor: 'pointer',
marginTop: '50px'
}; const mapStateToProps = (state) => ({
user: state.user,
address: state.address
}); const enhance = compose(
connect(mapStateToProps),
flattenProp('user')
); let User4 = enhance(({ name, status, address }) => (
<div style={UserStyle}>
{name} - {status} - {address.street} - {address.postcode}
</div>
)); export default User4;
'flattenPorp' helps to get single prop from object and spread its props.
最新文章
- 线性数据结构之栈——Stack
- Qt中 QString 和int, char等的“相互”转换
- .NET方向高级开发人员面试时应该事先考虑的问题
- 使用grep恢复被删除文件内容【转】
- android 小知识点
- 构造函数继承关键apply call
- HDU 1969 Pie(二分法)
- android开发工具类之获得WIFI IP地址或者手机网络IP
- Photography theory: a beginner&#39;s guide(telegraph.co.uk)
- leetcode Minimum Depth of Binary Tree python
- SB淘宝api的奇葩问题! 一则服务器无法访问淘宝api
- eclipse项目导入到android studio中文乱码处理
- 在Mac下配置Maven环境
- QT creator 其他资源(image)的添加以及简单利用
- MapReduce原理
- li下的ul----多级列表
- idea部署tomcat-404错误
- java jni调用
- cqlsh 一个错误
- Use JAWS 14 in a VM
热门文章
- Python 标准库 csv —— csv 文件的读写
- 8 Great Java 8 Features No One&#39;s Talking about--转载
- go pointer
- 推广一下新Blog www.hrwhisper.me
- BZOJ3626: [LNOI2014]LCA(树链剖分+线段树)
- 使用网络TCP搭建一个简单文件下载器
- StringBuilder类的使用总结
- upf用到的工具
- GO语言学习(十六)Go 语言结构体
- 不在JPA 的 persistence.xml 文件中配置Entity class的解决办法