【发布时间】: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[]) => {,它返回了一个包含大约 100 个元素的数组。我希望它只返回 ID 与 URL 相同的元素,而不是返回 100 个项目。所以只要我添加了.filter()函数,它现在什么都不返回。
标签: arrays reactjs typescript react-redux react-router