【问题标题】:ReactJS toLowerCase is not a functionReactJS toLowerCase 不是一个函数
【发布时间】:2016-05-16 20:31:37
【问题描述】:

我通过将我的文本转换为小写并将其索引与 -1 进行比较来进行比较,以便对 ReactJS 中的特定字段有一些价值,但我在 JavaScript 控制台中收到此错误:

未捕获的 TypeError:props.filterText.toLowerCase 不是函数

var props = this.props;
var rows = this.props.episodes
    .filter(function(episode){
        return episode.title.toLowerCase().indexOf(props.filterText.toLowerCase()) > -1;
    })
    .map(function(episode){
       return <EpisodeRow key={episode.title} episode={episode}/>
    });

【问题讨论】:

  • props.filterText 有什么价值?
  • episode.title 是字符串吗?尝试 episode.title.toString().toLowerCase() 或 console.log 它的值到控制台。
  • 这是一个非常简单的错误 - props.filterText 不是字符串。只需在props.filterText 的过滤器循环中执行console.log,您就会发现它不是字符串。我的猜测是undefined
  • @adam: undefined 会导致 RefError "undefined has no property toLowerCase" ... 吗?
  • 也可能是一个非常小的性能问题 - 但是如果您不必每次都在循环中.toLowerCase()var filter = props.filterText.toLowerCase() 在您的过滤器函数之外并在您的函数内执行 indexOf(filter)

标签: javascript html reactjs reactjs-native


【解决方案1】:

看起来克里斯的评论是正确答案:

如果 title 是字符串,请在 toLowerCase() 之前使用 toString()

return episode.title.toString().toLowerCase().indexOf(props.filterText.toString().toLowerCase()) > -1;

【讨论】:

  • 在我的特定情况下,此解决方案将文本呈现为“[Object] [Object]”。使用强类型语言编码时,您不应该猜测。
【解决方案2】:

我想我找到了问题:)

props.filterText 未定义。 => filterText:"" 必须在放入props之前的状态中声明

【讨论】:

  • 我又遇到了2次这个问题。
【解决方案3】:

我认为来自 cmets 的亚当的回答实际上是正确的,结果解决了我的问题:

.filter(function(episode){
    if(episode.title) {
        return episode.title.toLowerCase().indexOf(props.filterText.toLowerCase()) > -1;
    } else {
        return '';
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 2022-11-12
    • 2019-08-05
    • 1970-01-01
    • 2015-10-29
    • 2021-12-05
    • 2020-04-05
    • 2021-11-02
    相关资源
    最近更新 更多