javascript - 如何将组件道具从 React 传递到 Redux?
问题描述
尝试通过连接将组件(来自Table组件)的道具(只是一个字符串)传递给redux时,我不断收到一条错误消息,
我得到的错误输出是:
TypeError:无法读取未定义的属性“道具”
13 |
14 | const getTableData = (state) =>{
15 | return{
> 16 | fieldNames: state[this.props.tableHead]
17 | }
18 | }
19 |
表格组件在带有 props 的组件中调用:
<Table data = {'contacts'} tableHead = {'contactsKeyNames'}/>
表组件在哪里:
import React from 'react';
import '../../styles/App.css';
import {connect} from 'react-redux';
class Table extends React.Component{
render(){
return(
<div> hi </div>
)
}
}
const getTableData = (state) =>{
return{
fieldNames: state[this.props.tableHead]
}
}
export default connect(getTableData)(Table);
以及 redux 商店在哪里:
const initState = {
contacts:[
{
company: 'Rapid Precision Mfg.',
title: 'Quality Engineer',
firstName: 'Dongyob',
lastName: 'Lee',
officePh: '',
ext: '',
cell: '669-294-0910',
email: 'dyl4810@gmail.com'
},
{
company: 'Facebook',
title: 'Frontend Developer',
firstName: 'Edward',
lastName: 'Simmons',
officePh: '408-516-4662',
ext: '003',
cell: '669-252-4251',
email: 'edwardsimmons@gmail.com'
},
{
company: 'Amazon',
title: 'Data Scientist',
firstName: 'Harry',
lastName: 'Davis',
officePh: '',
ext: '',
cell: '408-344-2110',
email: 'harrydavis0@gmail.com'
},
{
company: 'Google',
title: 'Googler',
firstName: 'Katherine',
lastName: 'Jones',
officePh: '408-963-7156',
ext: '846',
cell: '408-828-0550',
email: 'katherinejones0@gmail.com'
},
{
company: 'Alibaba',
title: 'Scammer',
firstName: 'Eric',
lastName: 'Brown',
officePh: '510-663-5552',
ext: '462',
cell: '408-644-0110',
email: 'ericbrown@gmail.com'
},
],
contactsKeyNames:{
company: 'Company',
title: 'Title',
firstName: 'First Name',
lastName: 'Last Name',
officePh: 'Office',
ext: 'Ext',
cell: 'Cell',
email: 'Email'
}
};
const rootReducer = (state = initState, action) => {
return state;
};
export default rootReducer;
我试图通过如下设置构造函数将它绑定到道具,但没有奏效。
constructor(props){
super(props)
this.props = this.props.bind(this)
}
我究竟做错了什么?帮助!
解决方案
看看连接文档。您需要使用 ownProps 参数来访问 tableHead:
const getTableData = (state, ownProps) =>{
return{
fieldNames: state[ownProps.tableHead]
}
};
推荐阅读
- javascript - 如何使用 PHP 在 Google 表格图表中排序日期?
- numpy - 如何使用 Matplotlib 或其他在动画图中绘制不规则采样的时间数据?
- vim - 当我在vim中时,如何在光标下路径的位置打开一个shell?
- scala - if和elseif中的scala多个条件
- asp.net-core - 使用数据库上下文的依赖注入。如何在普通类中获取数据库上下文
- ember.js - Ember 插件中的 Pod 结构
- javascript - Node.js 中 ES6 模块的内联导入
- security - bcrypt 可能的密码组合数量
- javascript - 嵌套 json 需要借助 angular 以树结构格式动态显示
- tfs - TFS 构建管道在分离/重新附加集合后不排队