如何在无状态组件中访问mapStateToProps映射的props?
解决无状态组件访问Redux映射props的问题
嘿,这个问题其实很好解决,核心就两步,我给你拆解清楚:
1. 把test添加到组件的props解构中
你当前的组件参数只声明了readOnly和hasActionPoints,所以mapStateToProps映射的test并没有被组件接收。只需要在解构里加上test就行:
export const InfoPanelForm = ({ readOnly, hasActionPoints, test }) => ( <div> <Row> <Column> <VerticalSpacer space={4} /> <Element>Info</Element> {/* 现在可以直接在组件里使用test了 */} <Element>当前Test值:{test}</Element> </Column> </Row> </div> )
2. 确保组件和Redux Store正确连接
你只定义了mapStateToProps,但还需要用Redux的connect函数把组件和store绑定起来,否则映射的props不会传递到组件里。完整的代码应该是这样的:
import { connect } from 'react-redux'; import { formValueSelector } from 'redux-form'; // 你的组件定义 export const InfoPanelForm = ({ readOnly, hasActionPoints, test }) => ( <div> <Row> <Column> <VerticalSpacer space={4} /> <Element>Info</Element> <Element>当前Test值:{test}</Element> </Column> </Row> </div> ) // 映射state到props const mapStateToProps = state => ({ test: formValueSelector('InfoPanel')(state, 'test'), }); // 连接组件与Redux Store export default connect(mapStateToProps)(InfoPanelForm);
小提示:关于组件导出
如果你之前是通过命名导出(export const InfoPanelForm)引用组件,现在要注意:连接后的组件是默认导出的,所以在其他文件导入时要改成:
import InfoPanelForm from './InfoPanelForm';
如果需要保留原组件的命名导出(比如用于测试),可以同时保留两种导出方式,互不影响。
内容的提问来源于stack exchange,提问作者Leff
相关产品推荐
相关产品推荐

