尝试尝试.filter()时,TypeError:“无法读取未定义的属性'toLowerCase'”

时间:2019-07-30 21:52:47

标签: javascript reactjs redux typeerror

所以我一直在尝试解决此错误,而且我一直空白。我尝试用subreddit,键,链接,类型和主体替换.filter()中的标题,它们都可以正常工作而不会抛出错误,只有标题会给我错误。在故障排除期间,我还放置了console.log来查看是否确实存储了某些内容,并像应有的那样将标题打印到了控制台,但是save.title在.filter中仍然未定义。我也试过没有toLowerCase()的save.title.includes没有任何作用。

有问题的代码

  renderPostTitles = () => {
    const importantValues = this.props.totalUserSaves.map((saved) => {
      return { 
        subreddit: saved.data.subreddit, 
        title: saved.data.title, 
        key: saved.data.id, 
        link: `https://www.reddit.com${saved.data.permalink}`,
        type: saved.kind,
        body: saved.data.body
      }
    })

    console.log(importantValues[0].title)
    const threadsArray_searched = importantValues.filter(saved => saved.title.toLowerCase().includes(this.props.searchQuery.toLowerCase()) )

更多组件:

import React from 'react';
import { connect } from 'react-redux';

class DisplaySaves extends React.Component {
  renderPostTitles = () => {
    const importantValues = this.props.totalUserSaves.map((saved) => {
      return { 
        subreddit: saved.data.subreddit, 
        title: saved.data.title, 
        key: saved.data.id, 
        link: `https://www.reddit.com${saved.data.permalink}`,
        type: saved.kind,
        body: saved.data.body
      }
    })

    const threadsArray_searched = importantValues.filter(saved => saved.title.toLowerCase().includes(this.props.searchQuery.toLowerCase()) )

    return threadsArray_searched.map((saved, i) => {
     return (
        <div key={saved.key}>
          <div> {i+1}. </div>
          <div> r/{saved.subreddit}: </div>
          <p> <a href={saved.link} target="_blank" rel="noopener noreferrer"> {saved.title} </a> </p>
        </div>
        )
    })
  }

  render () {
    return (
      <div>
        <div>{this.renderPostTitles()}</div>
      </div>
      ) 
  }
}

const mapStateToProps = state => {
  console.log(state)
  return { 
    totalUserSaves: state.userData.totalUserSaves,
    searchQuery: state.userData.searchQuery
   }
}

export default connect(mapStateToProps)(DisplaySaves);

1 个答案:

答案 0 :(得分:2)

确保在所有情况下title都是一个字符串(未定义可能会潜入其中一个元素中),您可以使用默认或字符串构造函数:

return {
  title: saved.data.title || '', 

return {
  title: String(saved.data.title),