我对异步一窍不通,我不确定为什么我在尝试编写一个简单的异步方法时会在我的 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/