简体   繁体   中英

Can't display data from React Component

Try display props from react component. Need to show Tabs name Do this.

import React from 'react'
import { Link, browserHistory } from 'react-router'

import Tabs from '../../components/Tabs/Tabs'

 function Revenue ({ children }) {
  return (
    <div>
    <div>

              <Tabs items = { ['Home', 'Services', 'About', 'Contact us'] } />
          </div>
      <div className="cont-position">{children}</div>
    </div>

  )
}

export default Revenue

Tabs.js

import React from 'react'
import { Link, browserHistory,IndexLink } from 'react-router'

 function Tabs () {

  var data = this.props.items;
  var newsTemplate;
  newsTemplate = data.map(function(item, index) {
                return (
                    <div key={index}>
                        <li><Link to="/Revenue/IncomeOver" activeClassName="activelink">{item} </Link></li>
                    </div>
                )
            })

export default Tabs

But get error : Uncaught TypeError: Cannot read property 'props' of undefined

You are using the Stateless Function Components , so instead of using this.props , receive the props in the function arg, try this it will work:

function Tabs (props) {
    var newsTemplate=[], data = props;
    data.items.forEach(function(item, index) {
        newsTemplate.push (
            <div key={index}>
                <li>{item}</li>
            </div>
        )
    });
    return(<div>{newsTemplate}</div>);
} 

check the jsfiddle for working example: https://jsfiddle.net/4o6snef0/

check the article on Stateless Funcion Comp : https://www.reactenlightenment.com/react-state/8.4.html

It seems like you're trying to write your components as Stateless Functional Components . As the name suggests, your components are written as functions, not as classes. For this reason, you cannot use this .

As such, this is undefined, hence your warning " cannot read property 'props' of undefined ".

To access your props, simply add that as the function parameter in your function.

function Tabs (props) {

  var data = props.items;
  var newsTemplate;
  newsTemplate = data.map(function(item, index) {
    return (
      <div key={index}>
        <li><Link to="/Revenue/IncomeOver" activeClassName="activelink">{item} </Link></li>
      </div>
    )
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM