React组件类,不能写异步方法?

时间:2017-10-15 05:24:08

标签: javascript reactjs asynchronous

我对异步很朦胧,我不确定为什么在尝试编写一个简单的异步方法时,我的反应组件中出现了语法错误。

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

2 个答案:

答案 0 :(得分:2)

语法错误位于

 [difftool "DiffMerge"]
     cmd = 'C:/Program Files/SourceGear/Common/DiffMerge/sgdm.exe' "$LOCAL" "$REMOTE"
 [merge]
     tool = DiffMerge
 [mergetool "DiffMerge"]
     cmd = 'C:/Program Files/SourceGear/Common/DiffMerge/sgdm.exe' -merge -result="$PWD/$MERGED" "$PWD/$LOCAL" "$PWD/$BASE" "$PWD/$REMOTE"
     trustExitCode = true

.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()

答案 1 :(得分:0)

您的componentDidMount函数在语法上无效。您尚未为then电话提供适当的功能。此外,您的console.log应该在当时的通话中。