[英]After fetch state returns undefined
Im using fetch to post data to my local api, but when trying to get them and error like this occures. 我使用fetch将数据发布到本地api,但是尝试获取它们并出现此类错误。 In fetch i get result perfectly fine, but after that trying to pass that into state like below:
在获取中,我得到的结果非常好,但是之后尝试将其传递给如下所示的状态:
this.setState({ items: result.items }) this.setState({项目:result.items})
but items returns undefined and don't know why ?
但是项返回的是undefined并且不知道为什么?
My code: 我的代码:
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>
);
}
}
}
You can do either: 您可以执行以下任一操作:
this.setState({
items: result.items || [],
isLoaded: true
});
or 要么
{
items && items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.