【问题标题】:i got this problem i need help " this.state.pages.filter is not a function"我遇到了这个问题,我需要帮助“this.state.pages.filter 不是函数”
【发布时间】:2021-07-13 00:42:00
【问题描述】:

我遇到了这个问题,我需要帮助“this.state.pages.filter 不是函数”这是代码 -->

类 BlockEditor 扩展 React.Component {

constructor(props) {
    super(props);
    this.state = {
        pages: '',
        editor: false,
        page: '',
        pageId: props.match.params.pageId
    }
}

componentDidMount() {
    servicePage.getPage()
        .then( res => {
            this.setState({
                pages : res
            });

            if( this.state.pageId ) {
                this.state.pages.filter(page => page._id === this.state.pageId).forEach(page =>
                    this.setState({
                        page : page
                    })
                )
            }
        })

}

【问题讨论】:

  • 我认为.filter 仅适用于数组。检查stackoverflow.com/questions/55458675/filter-is-not-a-function/…
  • 请适当地格式化您的代码以提高您问题的可读性。如果您的问题难以阅读,贡献者不太可能提供帮助。另外,你能避免使用“我需要帮助”的短语吗?他们并没有真正为您的问题添加任何有用的信息。您能否也分享一下您迄今为止的尝试?

标签: reactjs


【解决方案1】:

this.state.pages 被初始化为字符串。
在这里,您尝试使用 filter 函数,该函数附加到 Array:Array.prototype.filter 的原型。
字符串上不存在过滤器函数,这解释了错误消息。

要解决此问题,您应该将页面声明为数组:

this.state = {
    pages: [] ,
    editor: false,
    page: '',
    pageId: props.match.params.pageId
}

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多