【问题标题】:ReactJs: TypeError: Cannot read property 'ItemsServices' of undefinedReactJs:TypeError:无法读取未定义的属性“ItemsServices”
【发布时间】:2020-07-24 15:26:16
【问题描述】:

这里我遇到了AliceCarousel 的一些问题,无法将我的回复映射到在图库中显示其图像。 我想为每个画廊显示各自类型的图像。

我一般都关注SO example

这里有什么帮助或建议可以使它成为可能吗? 提前谢谢。

//Js

class KitchenService extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentIndex: 0,
      responsive: { 1024: { items: 3 } },
      galleryItems: this.galleryItems(),
      services : this.props.resume,
      ...props,
      ItemsServices:[]
    }
  }

  static propTypes = {
    getService: PropTypes.func.isRequired,
    resume: PropTypes.object.isRequired,
    auth: PropTypes.object.isRequired,
    loading: PropTypes.object.isRequired
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if(nextProps.resume !== this.props.resume){
      var services  = this.props.resume.services;
      this.setState({
        ItemsServices: services
      })
    }
  }

  componentDidMount() {
    this.props.getService();  
  }

  slideTo = (i) => this.setState({ currentIndex: i })

  onSlideChanged = (e) => this.setState({ currentIndex: e.item })

galleryItems = () => {
    return this.state.ItemsServices.map((brand, i) => {
      var checkImage = brand.length !== 0 && brand.service_name === "Office";

      console.log(checkImage, "checkImage")
      return (
        <div key={`key-${i}`}  className="card-img-top"><img src={brand.service_image_url} /></div>
      )
    })
  };
 
  render() {
    const { responsive, currentIndex } = this.state
    const items = this.galleryItems();
    return(
        <div>
          <Grid className ="col-12 service-kitchen-gallery-grid" >
            <div className="service-gallery-headline">
                Kitchen
            </div>
              
            <AliceCarousel
              dotsDisabled={true}
              buttonsDisabled={true}
              items={items}
              responsive={responsive}
              slideToIndex={currentIndex}
              onSlideChanged={this.onSlideChanged}
              />
          </Grid>
        </div>
    )
  }
}

const mapStateToProps = (state) => ({
  resume: state.resume,
});

export default connect(mapStateToProps, {getService }) (KitchenService);

//错误

TypeError: Cannot read property 'ItemsServices' of undefined

服务 API 响应

(console.log(服务))

[
  {
    _id: "5f1971da18ba2b04704d65c2",
    service_name: "Other",
    service_image_url:
      "https://res.cloudinary.com/tammycloudinary/image/upload/v1595503076/nou0knjbtkujxwjktang.png",
    date: "2020-07-23T11:17:46.928Z",
    __v: 0,
  },
  {
    _id: "5f1971b218ba2b04704d65c1",
    service_name: "Bedroom",
    service_image_url:
      "https://res.cloudinary.com/tammycloudinary/image/upload/v1595503036/kfiteeilh4doytio6gs8.png",
    date: "2020-07-23T11:17:06.742Z",
    __v: 0,
  }
];

【问题讨论】:

  • 这不能解决问题,但您还需要从函数返回 - return this.state.ItemsServices.map...
  • 嗨@BrianThompson 谢谢你的时间。如果可能的话,请您详细说明您的答案。可能我在这里也遗漏了一些东西。
  • 好吧,您期望galleryItems() 的结果是分配给items 的东西,但函数galleryItems 不返回任何内容。您正在映射状态数组(或者自从它现在中断之后没有)但没有返回映射的结果。
  • 我已经更新了我的代码,但我得到了同样的错误。我仍然在这里遗漏什么吗?
  • 就像我说的那样,这不会修复当前的错误,但会修复这个错误修复之后出现的错误。我还没有看到任何可能导致它的东西。你能举一个可运行的例子吗?您可以在函数内控制台记录this 并将其输出添加到问题中吗?

标签: javascript reactjs redux


【解决方案1】:

问题不像我最初想的那样来自const items = this.galleryItems();。它来自构造函数。

您正在尝试使用状态对象来构建初始状态对象。这显然行不通。

  constructor(props) {
    super(props);
    this.state = {
      currentIndex: 0,
      responsive: { 1024: { items: 3 } },
      galleryItems: this.galleryItems(), // <-- Here is the problem
      services : this.props.resume,
      ...props,
      ItemsServices:[]
    }
  }

您尝试通过调用this.galleryItems 来初始化state。但该函数依赖于已声明的this.state。由于它尚未创建(但正在声明过程中),它是undefined,您会收到此错误。

我认为gallaryItems 根本不属于状态。通常不建议将 JSX 存储在 state 中。相反,只需使用 render 中的函数来计算每次渲染所需的 JSX。

另一个注意事项:不要在构造函数中使用this.props。而是使用传递给构造函数的props

【讨论】:

  • 谢谢。这确实是对我的错误的一个很好的解释。我真的很感激你的时间。我已删除 this.galleryItems 并且它工作正常,尽管过滤不适用于 var checkImage = brand.length !== 0 &amp;&amp; brand.service_name === "Office"; 。我一定会弄清楚的。再次感谢您。
【解决方案2】:

Y0u 也可以使用此解决方案解决此问题,也可以使用 filter

render() {
    const { services, loading} = this.props.resume;
    var checkImage = services.length === 0 ? [] : services.filter((item) => item.service_name === "Kitchen")
    return(
      <div>

            <OwlCarousel className="owl-theme" loop margin={10} nav>
               {checkImage.map((item, i) => ( 
                <div className="col-xs-12 item" key={item._id} data-id={item._id} >
                  <img className="service-gallery-images" src={item.service_image_url} alt=""/>
                </div>
            ))}
            </OwlCarousel>
      </div>
    )
  }

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多