gpt4 book ai didi

javascript - TypeError: "Cannot read property ' toLowerCase' of undefined"尝试.filter()时

转载 作者:行者123 更新时间:2023-11-30 13:56:05 24 4
gpt4 key购买 nike

所以我一直在尝试解决此错误,但一直一无所获。我尝试用 subreddit、键、链接、类型和正文替换 .filter() 中的标题,它们都可以正常工作而不会引发错误,只有标题给我错误。在故障排除期间,我还放置了那个 console.log 以查看是否实际存储了某些内容,并且它像应该的那样将标题打印到控制台,但 saved.title 在 .filter 中仍然未定义。我也试过 saved.title.includes 没有 toLowerCase() 无济于事。

有问题的代码

  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);

最佳答案

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

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

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

关于javascript - TypeError: "Cannot read property ' toLowerCase' of undefined"尝试.filter()时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57280522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com