【问题标题】:setState from .map inside componentDidMount()setState 从 .map 里面 componentDidMount()
【发布时间】:2018-11-10 13:13:21
【问题描述】:

我正在尝试找到在 componentDidMount 内的映射项目上使用 setState 的解决方案。

我正在使用 GraphQLGatsby 并返回许多 data 项目,但要求特定的 pathname===slug state 在组件中更新为匹配的 @ 987654330@.

propertyInit = () => {
  const pathname = location.pathname;
  return (
    <StaticQuery
      query={graphql`
        query {
          allContentfulProperties {
            edges {
              node {
                id
                slug
                information {
                  littleHotelierId
                }
              }
            }
          }
        }
     `}
      render={data => {
        data.allContentfulProperties.edges.map(({ node: property }) => {
          if (pathname === property.slug) {
            !this.isCancelled &&
              this.setState({
                littleHotelierId: property.information.littleHotelierId
              });
          }
          return null;
        });
      }}
    />
  );
};

然后我将其拉入componentDidMount

componentDidMount() {
  this.propertyInit();
}

不相关,但作为参考 this.isCancelled = true; 添加到 componentWillUnmount

我没有收到任何错误,但如果我 console.log(littleHotelierId) 我什么也得不到。

起初我确实认为这可能是因为 return 为 null 所以尝试给 map 一个 const 并返回为

render={data => {
  data.allContentfulProperties.edges.map(({ node: property }) => {
    if (pathname === property.slug) {
      const littleHotelier =
        !this.isCancelled &&
        this.setState({
          littleHotelierId: property.information.littleHotelierId
        });
      return littleHotelier;
    }
  });
}}

但这也失败了。

目标是 componentDidMount 将 GraphQL data 中返回的项目映射为

componentDidMount() {
  if (path1 === '/path-slug1') {
    !this.isCancelled &&
      this.setState({
        littleHotelierId: 'path-id-1'
    });
  }
  if (path2 === '/path-slug2') {
    !this.isCancelled &&
      this.setState({
        littleHotelierId: 'path-id-2'
    });
  }
  ... // other items
}

我认为问题在于 GraphQL 以异步方式获取数据,并且此请求未完成,因为 componentDidMount() 被调用。如果我console.log data 它不会向console 返回任何内容。我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs graphql gatsby


    【解决方案1】:

    我认为您需要创建一些过滤数据作为地图功能的结果。过滤数据后,您执行 setState({data: data})。做多个setState不好。

    如果您的 GraphQL 返回 Promise,那么您可以编写如下内容:

    componentDidMount() {
      this.fetchData()
        .then(data => {
           const filteredData = data.filter(element => 
             element.someProperty === propertyValue
           );
         this.setState({ data: filteredData });
        })
    }
    

    【讨论】:

    • filter 完全符合我的需要。干杯。
    猜你喜欢
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多