如何将组件道具从React传递到Redux?

时间:2019-03-12 21:01:47

标签: javascript reactjs redux

当尝试通过连接将组件(从Table组件)的props(只是一个字符串)传递到redux时,我不断收到错误消息

我得到的错误输出是:

  

TypeError:无法读取未定义的属性“ props”

  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;

我试图通过如下设置构造函数将其绑定到prop,但是没有用。

constructor(props){
    super(props) 

    this.props = this.props.bind(this)
  }

我在做什么错? 救命!

2 个答案:

答案 0 :(得分:2)

看看connect docs。您需要使用ownProps参数来访问tableHead:

const getTableData = (state, ownProps) =>{
  return{
   fieldNames: state[ownProps.tableHead]
  }
};

答案 1 :(得分:1)

您还应该确保您的组件已正确注册并通过提供者。