【问题标题】:Typescript React - Check if route path exists in arrayTypescript React - 检查数组中是否存在路由路径
【发布时间】:2020-04-13 16:31:35
【问题描述】:

这是我的数组的一个示例(我简化了数组,但大约有 100 个元素,每个元素大约有 20 个值:

0:
odata.type: "SP.Data.ProductListItem"
Title: "This is Product 1"
Id: 1

1:
odata.type: "SP.Data.ProductListItem"
Title: "Dell Computer"
Id: 2

url 路径是mysite.com/product/2 我创建了一个产品组件,我想检查并查找数组中是否存在product/:id 并匹配URL 以显示该产品的信息。

因此,如果您访问/product/1',您会看到带有相应信息的This is Product 1 标题,如果您访问product/2,您会看到戴尔计算机。

在我的代码中,我试图保存数组的状态,因为我将添加一个允许某些用户更新此页面信息的表单。

pnp.sp.web.lists.getByTitle("Product") 工作正常,我无法让过滤器工作。

import * as React from 'react';
import { default as pnp, sp } from "sp-pnp-js";

export class Product extends React.Component<{ match: any }, {
  foundProduct: any,
}> {

  constructor(props) {
    super(props);
    this.state = {
      foundProduct: [],
    };
  }

  public componentDidMount() {
    const foundProduct = pnp.sp.web.lists.getByTitle("Product")
      .items
      .filter("Id eq '" + this.props.location.pathname, +"'")
      .top(1)
      .get()
      .then((items: any[]) => {
        this.setState({ foundProduct: [...foundProduct] });
      })
  }


  public render(): React.ReactElement<{}> {
    console.log(this);
    return (
      <div>
        <div className={styles.colHalf}>
          { this.state.foundProduct.ID }
        </div>
        <div className={styles.colHalf}>
          { this.state.foundProduct.Title}
        </div>
      </div>
    );
  }
}

【问题讨论】:

  • 看来您想将items 传递给setState 内的then
  • @Shlang 我遇到了.filter("ID eq '" + this.props.location.pathname, + "'") 的问题,它没有返回任何内容。
  • 你能说得更具体点吗?你能指望什么?你怎么理解它什么都不返回?至于现在,您似乎希望它返回您要分配给foundProduct 的值,然后在setState 内部使用该值`then 但js 不能这样工作。
  • @Shlang 是的,对此我很抱歉,所以我使用了pnp.sp.web.lists.getByTitle("Products").items.get().then((items: any[]) =&gt; {,它返回了一个包含大约 100 个元素的数组。我希望它只返回 ID 与 URL 相同的元素,而不是返回 100 个项目。所以只要我添加了.filter() 函数,它现在什么都不返回。

标签: arrays reactjs typescript react-redux react-router


【解决方案1】:

过滤器内部的条件不清楚, 也许你应该这样做:

(我不确定this.props.location.pathname的内容)

public componentDidMount() {

        const foundProduct = pnp.sp.web.lists.getByTitle("Product").items.filter(item=>item.Id==this.props.location.pathname).top(1).get().then((items: any[]) => {

            this.setState({ foundProduct: [...foundProduct] });

        })          
    }

希望对你有帮助。

【讨论】:

  • 谢谢!我最终使用了filter("Id eq '" + this.props.match.params.id + "'"),对我应该使用location.pathname还是match.params.id有任何想法?
  • 我不确定您的数据结构,但如果this.props.match.params.id 包含Id ,那可能就是您需要的。另一件事,您是否有重复的密钥需要做.top(1)
  • 谢谢,我搞定了。我没有重复的钥匙。我添加了.top(1),因为我希望它搜索数组,并且一旦它找到停止过滤的键。由于数组将包含 100 多个元素,我认为这会提高性能还是不是问题?如果 ID 是数组中的第二项,我希望它停止过滤。并继续
  • 我相当肯定filter()为数组中的每个元素调用一次提供的回调函数(see here),考虑使用find():“find方法执行回调函数数组的每个索引一次,直到回调返回一个真值”related question
猜你喜欢
  • 2022-11-14
  • 2020-07-27
  • 1970-01-01
  • 2019-04-03
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多