.filter(...)。then不是componentDidMount

时间:2018-11-10 10:43:25

标签: javascript reactjs

我试图在返回的项目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

3 个答案:

答案 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 })
  });
}

Array.filter reference

答案 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 });
}