【发布时间】:2019-01-08 21:10:15
【问题描述】:
我正在使用 fetch 将数据发布到我的本地 api,但是在尝试获取它们时会发生这样的错误。在 fetch 我得到的结果非常好,但之后试图将其传递到如下状态:
this.setState({ 项目:result.items })
但是 items 返回 undefined 并且不知道为什么?
我的代码:
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
error: null,
isLoaded: false
};
this.setState = this.setState.bind(this);
}
componentDidMount() {
fetch("http://localhost:3000/items")
.then(res => res.json())
.then(result => {
console.log(result);
this.setState({
items: result.items,
isLoaded: true
});
console.log(this.state.items)
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
<h1>Saved items:</h1>
{
items && items.map(item => (
<li key={item.name}>
item: {item.name} {item.price}
</li>
))
}
</ul>
);
}
}
}
【问题讨论】:
-
看起来
result.items未定义 - 在设置状态之前添加日志 -
我做了,结果应该是这样
-
但是你是对的
-
我遇到了类似的问题,结果未定义。
标签: javascript reactjs undefined fetch setstate