You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用connect关联GraphQL结果到Redux时出现Cannot read property 'bind'错误

问题分析与修复方案

你遇到的Cannot read property 'bind' of undefined错误,以及代码里的潜在问题,我帮你梳理清楚:

1. 核心错误:connect与graphql高阶组件的组合方式错误

connect(来自react-redux)的第一个参数需要是**mapStateToProps函数**(或者null/不传,表示不需要从Redux映射状态),但你直接把graphql返回的高阶组件传给了它。这会导致connect内部试图对一个非函数值调用bind方法,从而抛出错误。

正确的做法是把这两个高阶组件组合起来,而不是嵌套错误。

2. 次要问题:graphql配置的语法错误

你在options函数里写了fetchPolicy: 'network-only';,这行代码的位置完全错误——它应该被包含在return的配置对象内部,而不是作为单独的语句存在,否则Apollo Client根本不会读取这个配置。

修复后的完整代码

import { connect } from 'react-redux';
import { graphql, compose } from 'react-apollo'; // 确保导入react-apollo的graphql和compose

class PhotoGrid extends React.Component {
  render () {
    const { data } = this.props;
    const isNewPage = this.props.location.pathname.includes('new');
    
    if (data.loading) {
      return <p>Loading ...</p>;
    }
    if (data.error) {
      return <p>{data.error.message}</p>;
    }
    
    return (
      <div>
        <div>Total record count: {data._allPostsesMeta.count}</div>
        <div className="photo-grid">
          { data.allPostses.map( (post,i) => <Photo {...this.props} key={i} postIndexID={i} post={post} />) }
        </div>
        {isNewPage && (
          <div>
            <div onClick={() => this.previousPage()}> Previous </div>
            <div onClick={() => this.nextPage()}> Next </div>
          </div>
        )}
      </div>
    );
  }
};

const allPostsCommentsQuery = graphql(All_Posts_Comments_Query, {
  options: ownProps => {
    const page = parseInt(ownProps.match.params.page, 10);
    const isNewPage = ownProps.location.pathname.includes('new');
    const skip = isNewPage ? (page - 1) * parseInt(PRODUCTS_PER_PAGE) : 0;
    const first = isNewPage ? parseInt(PRODUCTS_PER_PAGE) : parseInt(PRODUCTS_PER_PAGE);
    const orderBy = isNewPage ? OrderBy : null;
    
    // 把fetchPolicy放到返回的配置对象里
    return {
      variables: {
        __offline__: true,
        first,
        skip,
        orderBy,
      },
      fetchPolicy: 'network-only'
    }
  },
});

// 使用compose组合两个高阶组件(推荐方式,可读性更高)
export default compose(
  connect(null, null), // 不需要从Redux映射状态或方法,传null即可
  allPostsCommentsQuery
)(PhotoGrid);

// 如果你不想用compose,也可以这样写:
// export default connect()(allPostsCommentsQuery(PhotoGrid));

额外提醒

  • 确保你已经正确安装并导入了react-apollo(apollo-client本身不提供graphql高阶组件,需要依赖react-apollo);
  • 检查All_Posts_Comments_Query、OrderBy、PRODUCTS_PER_PAGE这些变量是否已经正确定义并导入,避免后续出现未定义的错误。

内容的提问来源于stack exchange,提问作者TheoG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:31:01