【发布时间】:2020-05-15 02:15:48
【问题描述】:
来自 Java 背景的我(非常)新反应。我正在尝试重构一些现有代码以使用异步和等待。
错误出现在我的渲染函数()(用 ***** 突出显示)之前,并且我得到一个“/src/App.js: Unexpected token, expected”,错误和无法终生弄清楚发生了什么。我试过弄乱 } ) 和 ; 并不能完全追踪它。感谢任何帮助。
import React, { Component } from "react";
import { FixedSizeGrid } from "react-window";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
specialties: [],
isLoaded: false,
error: null
};
}
async componentDidMount() {
const response = await fetch (url)
.then(response => response.json())
.then(body => {
const specialties = body.data.specialties;
return specialties;
})
.then(specialties => {
return specialties.map(({ _id, name }) => {
return [_id, name];
})
.then(transformed => {
this.setState({
specialties: transformed,
isLoaded: true,
error: null
});
})
.catch(error => {
this.setState({
specialties: [],
isLoaded: true,
error: error
});
});
}
render() {***********************here
if (this.state.error) {
return <span style={{ color: "red" }}>{this.state.error.message}</span>;
}
if (!this.state.isLoaded) {
return "Loading...";
}
const ITEM_HEIGHT = 35;
return (
<FixedSizeGrid
columnWidth={300}
rowHeight={35}
itemData={this.state.specialties}
height={ITEM_HEIGHT * this.state.specialties.length}
width={600}
itemSize={() => ITEM_HEIGHT}
columnCount={2}
rowCount={this.state.specialties.length}
>
{SpecialtyYielder}
</FixedSizeGrid>
);
}
}
const SpecialtyYielder = ({ columnIndex, rowIndex, data, style }) => {
return (
<div
style={{
...style,
backgroundColor:
(rowIndex + columnIndex) % 2 ? "beige" : "antiquewhite",
display: "flex",
alignItems: "center",
justifyContent: "center"
}}
>
{data[rowIndex][columnIndex]}
</div>
);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
【问题讨论】:
-
在执行 async/await 时不要使用
.then,这就是重点。你把它当作同步代码来对待 -
Ya.. 如果您不使用 fetch 的响应,为什么还要在那里使用 await fetch? await 实际上什么都不做
标签: javascript reactjs