【问题标题】:React: TypeError for split : Cannot read properties of undefined (reading 'split')反应:拆分的类型错误:无法读取未定义的属性(读取“拆分”)
【发布时间】:2021-10-11 20:38:29
【问题描述】:

我正在尝试通过 api 获取数据,并且我做到了。但是,我有分裂的问题。我尝试了一切,但仍然出现此错误。我怎样才能做到这一点?

编辑:我安装了这个 $npm add react-split 并像这样导入它:import Split from '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 
    });
}

【问题讨论】:

  • 错误是什么?
  • TypeError: 无法读取未定义的属性(读取“拆分”)
  • 表示变量url未定义
  • 我没有这样定义它: const {name, url} = this.props;
  • 如果你console.log this.props 你会看到没有url

标签: reactjs typescript react-native split


【解决方案1】:

请确保调用此PokemonDetail 的父组件发送具有相同名称的道具。

这样

class Pockemon extend Component {

render(){
   return (
     <>
       <PokemonDetail
          name='Pockemon name' // this line 
          url='the url' // and this line
       />

     </>
   )
}

}


【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2015-07-04
      相关资源
      最近更新 更多