javascript - React组件类,不能写async方法?

标签 javascript reactjs asynchronous

我对异步一窍不通,我不确定为什么我在尝试编写一个简单的异步方法时会在我的 React 组件中遇到语法错误。

class Locations extends React.Component {
  constructor(props) {
    super(props);

    this.searchProducts = this.searchProducts.bind(this);

  }

    async searchProducts(product_name, storeId) {
    let response =  await axios.get(
      `https://api.goodzer.com/products/v0.1/search_in_store/?storeId=${storeId}&query=${product_name}&apiKey=125cbddf3880cb1ba652a7c269ba1eb0`
    );
    console.log(response);
    return response.data.products;

}

  componentWillMount() {
    let products = [];
    this.props.searchLocations(this.props.navigation.state.params.product_name, this.props.navigation.state.params.searchRadius)
      .then(
          products = (this.props.locations.map(
          location => ({[location.id]: this.searchProducts(
            this.props.navigation.state.params.product_name, location.storeid
          )}))
        )
      );

      console.log(products);
  }

  render() {
    const displayLocations = this.props.locations.map(
      location => (<Text key={location.id}>{location.name}</Text>)
    );
    return (
      <View>
        <Text>HELLO</Text>
        <View>{displayLocations}</View>
      </View>
    );
  }
}

我收到一个语法错误:'意外的标记,预期的 ('。

我不明白这与此处给出的示例有何不同:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function

最佳答案

语法错误在

  .then(
      products = /* missing `>` at arrow function */ (this.props.locations.map(
      location => ({[location.id]: this.searchProducts(
        this.props.navigation.state.params.product_name, location.storeid
      )}))
    )
  )

.then() 需要一个函数作为参数,this.searchProducts() 返回一个 Promise 对象,async也需要在.map()回调函数

中设置
async componentWillMount() {
  let products = await this.props
  .searchLocations(
    this.props.navigation.state.params.product_name, 
    this.props.navigation.state.params.searchRadius
  )
  .then(
    () => 
        Promise.all(this.props.locations.map(async(location) =>
          ({[location.id]: await this.searchProducts(
            this.props.navigation.state.params.product_name, 
            location.storeid
          )}))
        )
  );
  console.log(products);
}

关于javascript - React组件类,不能写async方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46751990/

相关文章:

javascript - webpack 缩小 React 中选择性文件的全局变量和方法

reactjs - 从 apollo-client 中的客户端缓存中删除项目的正确方法

javascript - KineticJS 如何从图层获取颜色(来自图层的颜色选择器)

javascript - 如何获取组件高度来触发 React 中的 Headroom?

c# - 异步读取输出时外部进程阻塞主线程

c# - 通过 WebAPI 异步调用进程

android - 如何异步运行 FilterQueryProvider 的查询?

javascript - 如何降低 JavaScript 代码中的循环复杂度?

javascript - JQuery 检测空 p 标签

javascript - 全局函数在函数内部不可见