reactjs - 反应:拆分的类型错误:无法读取未定义的属性(读取“拆分”)
问题描述
我正在尝试通过 api 获取数据,并且我做到了。但是,我有分裂的问题。我尝试了一切,但仍然出现此错误。我怎样才能做到这一点?
编辑:我安装了这个$npm add react-split 并像这样导入它:从'react-split'导入拆分。 这是它在代码中的用法:
import React, {Component} from "react";
import { Link } from "react-router-dom";
class PokemonDetail extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
imgUrl: '',
pokemonIndex: '',
};
}
componentDidMount() {
const {name, url} = this.props;
const pokemonIndex = url.split('/')[url.split('/').length - 2];
const imageUrl = `https://github.com/PokeAPI/sprites/blob/master/sprites/pokemon/${pokemonIndex}.png?raw=true`;
this.setState ({
name: name,
imageUrl: imageUrl,
pokemonIndex: pokemonIndex
});
}
解决方案
我通过在拆分前插入问号解决了这个问题。我不知道原因,但它奏效了。
const pokemonIndex = url?.split('/')[url?.split('/').length - 2];
感谢所有回复我帖子的人。
推荐阅读
- javascript - 我的导航切换器图标未显示,但在单击该区域时它工作正常。我能做些什么来解决这个问题
- c# - 调用 async EventHandler 的区别
- ruby-on-rails - 使用 find .where 后如何获取活动记录的名称
- java - Java Servlet 如何通过 Session 获取 UserId
- python - 如何使用pyaudio在macos上录制麦克风?
- flutter - 无法在 macOS Catalina 10.15.4 上安装 dart
- javascript - Html Webpack Plugin 呈现 JS 模块而不是 HTML 文件
- c++ - 如何将一个类的成员函数作为参数传递给另一个类的成员函数?
- reactjs - 使用 docker run 命令启动开发服务器后,React 脚本立即退出
- java - 从 SB 2.2.7 升级到 SB 2.3.0 后 Spring Boot 应用程序不会启动