属性'match'在类型"Readonly<{}> & Readonly<{ children?: ReactNode; }>



所以我最近将一个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;
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;

最新更新