简体   繁体   中英

TypeError: Cannot read property 'props' of undefined reactjs

so i have recently started to learn react and i wanted to change the App component and this error popped out

TypeError: Cannot read property 'props' of undefined

here's the code: app.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App(){
  return (
    <div className="App">
      <header className="App-header">
        <p> hello  {this.props.yourName} </p>
      </header>
    </div>

and the index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

let yourName="yourName";

ReactDOM.render(
 <App yourName />,
  document.getElementById('root')
);
serviceWorker.unregister();

Unlike other cases in javascript which treating object with same "address" and "context" is in one place, in sending props if you send only


   <App yourName >

it comes in { props.yourName == true }, and not with the string value you sent.

change it to


      <App yourName={yourName}/>

and remove { this } keyword from { App } which is function and not class


import React from 'react';
import logo from './logo.svg';
import './App.css';

function App(props){
 return (
  <div className="App">
    <header className="App-header">
      <p> hello  {props.yourName} </p>
    </header>
  </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