使用状态在呈现中解析组件 DidMount 值



我是使用反应的新手。我想从火碱获取内容并在渲染中解析它。所以我尝试:

constructor(props) {
super(props);
this.state = {
loading: true,
data: null
}
}

componentDidMount() {
var feedRef = firebase.database().ref().child('posts').limitToLast(10);
feedRef.once('value', async function(snapshot) {
this.setState({ data: snapshot.val(), loading: false }); // error Unhandled Rejection (TypeError): Cannot read property 'setState' of null
});
}
render() {
return this.state.loading ? (
<div>
<Spinner />
</div>
) : (
<>
<div>
// how to put firebase content here?
</div>
</>
);
}

我想从Firebase获取内容(用户名,img(并将其放置在渲染中。我该怎么做?

可以使用 map 函数遍历数据状态并呈现数据状态中的项列表。
请务必使用${item.WHATEVER_YOUR_FIELD_IS}内部地图功能。

<div>
{this.state.data.map(item => {
return(
<div>
<h1>${item.username}</h1>
<img src=`${item.imgURL}`/>
</div>
)
})}
</div>

您将常规函数传递给feedRef.once,它会得到自己的this。 您应该使用箭头函数:

feedRef.once('value', async (snapshot) => {

或将this保存在其他变量中:

const me = this;
feedRef.once('value', async function(snapshot) {
me.setState({ data: snapshot.val(), loading: false }); // error Unhandled Rejection (TypeError): Cannot read property 'setState' of null
});

最新更新