简体   繁体   中英

TypeError: Cannot read property 'map' of undefined on React.js

I'm following a tutorial online for React.js on controlled inputs and I am repeatedly getting the error

TypeError: Cannot read property 'map' of undefined

import CallRow from "./CallRow";
import React from "react";

class SearchPage extends React.Component {
  constructor() {
    super();
    this.state = {
      search: "Level Up"
    };
  }

  updateSearch(event) {
    this.setState({ search: event.target.value.substr(0, 20) });
  }

  render() {
    return (
      <div>
        <ul>
          {this.props.calls.map(call => (
            <CallRow call={call} key={call.id} />
          ))}
        </ul>
        <input
          type="text"
          value={this.state.search}
          onChange={this.updateSearch.bind(this)}
        />
      </div>
    );
  }
}

export default SearchPage;

You should add props when calling super , also you not showing the whole application logic, are props.calls are even defined?

class SearchPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      search: "Level Up"
    };
  }
...

It seems that the call prop undefined.

Before map the prop value, check if it is undefined or not.

Please refer below code:

<ul>
    {(this.props.calls || []).map(call => (
        <CallRow call={call} key={call.id} />
    ))}
</ul>

1 check if you add the props into the component SearchPage as

<SearchPage calls ={arry}/>

and cleck if this array or not 2add in

constructor(props) {
    super(props);

after the make destructer for props by this const {calls}=this.props; then check the value of the calls if it pass as props by used console.log(calls)

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