首页 > 解决方案 > 反应:拆分的类型错误:无法读取未定义的属性(读取“拆分”)

问题描述

我正在尝试通过 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 
    });
}

标签: reactjstypescriptreact-nativesplit

解决方案


我通过在拆分前插入问号解决了这个问题。我不知道原因,但它奏效了。

        const pokemonIndex = url?.split('/')[url?.split('/').length - 2];

感谢所有回复我帖子的人。


推荐阅读