属性'match'在类型'Readonly <{}>和Readonly <{children?中不存在:ReactNode; }>

时间:2019-09-24 09:51:09

标签: javascript reactjs typescript

因此我最近将ReactJs项目从ES6 JavaScript转换为TypeScript,并且遇到了一堆必须解决的错误。发生的最后错误之一,我似乎无法在代码段中找到解决方法

async componentDidMount() {
    const { pokemonIndex } = this.props.match.params;

    // Urls for pokemon information
    const pokemonUrl = `https://pokeapi.co/api/v2/pokemon/${pokemonIndex}/`;
    const pokemonSpeciesUrl = `https://pokeapi.co/api/v2/pokemon-species/${pokemonIndex}/`;

    // Get Pokemon Information
    const pokemonRes = await axios.get(pokemonUrl);

    const name = pokemonRes.data.name;
    const imageUrl = pokemonRes.data.sprites.front_default;

    let { hp, attack, defense, speed, specialAttack, specialDefense }: any = "";

    pokemonRes.data.stats.map(
      (stat: { [x: string]: any; stat: { name: any } }) => {
        switch (stat.stat.name) {
          case "hp":
            hp = stat["base_stat"];
            break;
          case "attack":
            attack = stat["base_stat"];
            break;
          case "defense":
            defense = stat["base_stat"];
            break;
          case "speed":
            speed = stat["base_stat"];
            break;
          case "special-attack":
            specialAttack = stat["base_stat"];
            break;
          case "special-defense":
            specialDefense = stat["base_stat"];
            break;
          default:
            break;
        }
      }
    );

更具体地说,就行

const { pokemonIndex } = this.props.match.params;

这是什么原因?

----------------编辑------------------------------ ----

下面的代码是我的App.tsx的代码,其中包含我使用过的路由

import React, { Component } from "react";
import "./App.css";
import NavBar from "./components/layout/NavBar";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import Dashboard from "./components/layout/Dashboard";
import { HashRouter as Router, Route, Switch } from "react-router-dom";
import Pokemon from "./components/pokemon/Pokemon";

class App extends Component {
  constructor() {
    super({});
    this.state = {};
  }

  render() {
    return (
      <Router>
        <div className="App">
          <NavBar />
          <div className="container">
            <Switch>
              <Route exact path="/" component={Dashboard} />
              <Route exact path="/pokemon/:pokemonIndex" component={Pokemon} />
              <Dashboard />
            </Switch>
          </div>
        </div>
      </Router>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

type TRouteParams = {
    pokemonIndex: string; // since it route params
}

然后,您可以将这种类型用于RouteComponentProps的接口this.props.match.params

interface IPokemonPageProps extends RouteComponentProps<TRouteParams>, React.Props<TRouteParams> {
    ....
}

现在您应该可以像这样访问道具了:

const { pokemonIndex } = this.props.match.params;