子组件中未定义的prop值

时间:2018-09-08 15:19:47

标签: reactjs react-router

我正在尝试通过道具读取子组件中的数组项。将数组记录到子组件中即可。但是,如果我尝试通过使用match.params中的:id对其进行索引来访问其中一个数组项的属性,它将告诉我无法访问“未定义”的属性。

任何指导将不胜感激。

tours.js

import React, { Component } from "react";
import { Route, Switch } from "react-router-dom";

// Page Imports
import Summary from "../pages/summary";
import Details from "../pages/details";

// Component Imports
import Homebutton from "../components/homebutton";

class Tours extends Component {
  state = {
    tours: []
  };

  componentDidMount() {
    window.scrollTo(0, 0);
    fetch("/tours")
      .then(res => res.json())
      .then(res => this.setState({ tours: res }));
  }

  render() {
    const tours = this.state.tours;

    return (
      <section className="tours-page">
        <div className="center-box">
          <h2>Tours</h2>
        </div>
        <Switch>
          <Route
            exact
            path={this.props.match.url}
            render={props => <Summary {...props} tours={tours} />}
          />
          <Route
            path={this.props.match.url + "/:id"}
            render={props => <Details {...props} tours={tours} />}
          />
        </Switch>
        <Homebutton />
      </section>
    );
  }
}

export default Tours;

details.js

import React from "react";

const Details = ({
  tours,
  match: {
    params: { id }
  }
}) => (
  <section className="details">
    <h2>{tours[id]["name"]}</h2>
  </section>
);

export default Details;

2 个答案:

答案 0 :(得分:1)

为确保tours[id]不是undefined,请先检查

<section className="details">
 <h2>{tours[id] && tours[id]["name"]}</h2>
</section>

答案 1 :(得分:0)

componentDidMount总是在第一个render之后被调用时,您必须验证道具以防止应用程序崩溃:


const Details = ({
  tours,
  match: {
    params: { id }
  }
}) => (
  <section className="details">
    <h2>{tours.length && tours[id]["name"]}</h2>
  </section>
);