首页 > 解决方案 > 如何将组件道具从 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)
  }

我究竟做错了什么?帮助!

标签: javascriptreactjsredux

解决方案


看看连接文档。您需要使用 ownProps 参数来访问 tableHead:

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

推荐阅读