我试图在返回的项目filter
的{{1}}和componentDidMount
then
内的setState
内创建一个数组
propertyID
但收到此错误
未捕获的TypeError:properties.filter(...)。则不是函数 在ProxyComponent.componentDidMount
componentDidMount() {
const pathname = "/path2";
const properties = this.props.properties;
properties
.edges
.filter(node => {
return `/${node.slug}` === pathname;
})
.then(node =>
this.setState({ propertyID: node.information.propertyID })
);
}
为
this.props.properties
答案 0 :(得分:1)
您必须按如下所示更改“过滤器”的行,它将起作用。在过滤器功能中,请注意我如何使用{}表示法使用节点对象
在您的情况下,“节点”代表整个对象
{
"node": {
"id": "121323",
"slug": "path1",
"information": {
"propertyID": "property1"
}
}
}
但是您需要此对象的“节点”,这就是在过滤器功能中添加{}的原因。
解决方案-
var properties = {
"edges": [
{
"node": {
"id": "121323",
"slug": "path1",
"information": {
"propertyID": "property1"
}
}
},
{
"node": {
"id": "332342",
"slug": "path2",
"information": {
"propertyID": "property2"
}
}
},
{
"node": {
"id": "123234",
"slug": "path3",
"information": {
"propertyID": "property3"
}
}
}
]
}
console.log(properties
.edges
.filter(({ node }) => `/${node.slug}` === '/path1'))
答案 1 :(得分:0)
Array.filter不返回承诺。将您的代码更改为可运行:
componentDidMount() {
const pathname = "/path2";
const properties = this.props.properties;
const filteredArray = properties
.edges
.filter(node => {
return `/${node.slug}` === pathname;
});
filteredArray.forEach((node) => {
// Computed property, so each node gets set separately in state
this.setState({ [node.information.propertyID]: node.information.propertyID })
});
}
答案 2 :(得分:0)
尝试一下。
componentDidMount() {
const pathname = '/path2';
const properties = this.props.properties;
const node = properties.edges.filter(node => {
return `/${node.slug}` === pathname;
});
this.setState({ propertyID: node.information.propertyID });
}