Reactjs Can';t将从Firestore获取的状态数据设置为render()

Reactjs Can';t将从Firestore获取的状态数据设置为render(),reactjs,firebase,google-cloud-firestore,Reactjs,Firebase,Google Cloud Firestore,我想用Firestore获取一些数据,然后将这些数据设置为this.setState()。但这是无法呈现的 我的代码: class Item extends Component { constructor(props) { super(props); this.state = { item: null, } let self = this; const { id } = this.props.match.params; fire

我想用Firestore获取一些数据,然后将这些数据设置为
this.setState()
。但这是无法呈现的

我的代码:

class Item extends Component {
  constructor(props) {
    super(props);
    this.state = {
       item: null,
    }

    let self = this;
    const { id } = this.props.match.params;
    firebase
      .firestore()
      .collection("items")
      .doc(id)
      .get()
      .then(function(doc) {
        self.setState({
          item: doc.data()
        });
      });
  }
}

render() {
  console.log("item", this.state.item);
  // null
  return(
    <p>{item.name}</p>
  )
}
在上述代码中,您没有更新项目。是否可以按以下方式修改

self.setState({
              item: doc.data()// or any value using doc as per your needs
            });

你应该使用
componentDidMount
并在
之后添加
catch
,看看它是否抛出任何错误问题解决了???@RajanLagah非常感谢,我会尝试添加它。@PrakashKarena谢谢!我真的很感激你的帮助,但我做不到。所以我试着考虑另一种方法。他说他已经使用了<代码>组件Noths<代码>失败。@ RajanLagah Lagah,如果他从道具获得ID,那么请求将被发送给FiffBasthAK你!我真的很感谢你的帮助,这仍然是个问题。但我正在努力解决这个问题。
self.setState({
          room: doc.data()
        });
self.setState({
              item: doc.data()// or any value using doc as per your needs
            });
getDerivedStateFromProps = (props, state) =>  {
const { id } = props.match.params;
if(id){
firebase
  .firestore()
  .collection("items")
  .doc(id)
  .get()
  .then(function(doc) {
    this.setState({
      item : doc.data()  // use item here 
    });
  })
  .catch(err=>console.log(err))
 }
}