【发布时间】:2020-01-22 10:56:12
【问题描述】:
在componentDidMount 中编译定义变量都失败。我做了很多其他方法。似乎没有一个适用于我的特定代码。我认为阅读比试图解释更好。
import React from 'react';
import { connect } from './api';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
giphy: []
}
}
componentDidMount(){
connect(message => {
this.setState({
giphy: message
})
});
var Items = this.state.giphy.map(function(gif){ // items is not defined.
return <li>{gif}</li>;
})
}
render () {
return (
<div className=".App-logo">
<ul>
{ Items } // I wanted to show all items inside the array of objects.
</ul>
<ul className=".App-logo">
// the following method works. We need to make sure to check for this conditions or wont work
{this.state.giphy && this.state.giphy.length > 0 &&
<img src={ this.state.giphy[2].images.original.url}
alt="giphy.com animations"/>}
</ul>
</div>
)
}
}
如果我删除项目,它将显示状态中的第二个项目。 你能帮忙展示一下状态吗?
【问题讨论】:
-
您需要在 setState 上使用回调,您的数组未填充。 `setState({}, () => { 此处映射状态}).
-
您好,请检查我的解决方案,如果有帮助,请告诉我。
标签: arrays reactjs javascript-objects