【问题标题】:Why does it display only the last value of the array, and not the whole?为什么它只显示数组的最后一个值,而不是整个?
【发布时间】:2017-10-29 21:09:40
【问题描述】:

为什么它只显示数组的最后一个值,而不是整个? 当你更新数据库中的值时,当你更新数据库中的值时,它会输出所有

constructor(props) { 
    super(props); 
    this.name = this.props.name; 
    this.state = {[this.name] : []}; 
} 

componentDidMount() { 
    let cardQuantity = 
    firebase.database().ref("Users").child(this.name); 

    cardQuantity.on('value',snap => { 

        snap.forEach((childSnapshot)=> { 

            let card = {text: childSnapshot.val(), id: childSnapshot.key}; 

            this.setState({[this.name] :[card].concat(this.state[this.name])}); 
        });
    }); 
} 

render(){ 

    return ( 
        this.state[this.name].map( card => <h2 key={card.id}>{card.text}</h2>) 
    );
}

【问题讨论】:

    标签: reactjs firebase-realtime-database


    【解决方案1】:

    setState() 是异步的,所以你必须使用setState 的回调形式,如下所示:

    this.setState(prevState => ({
      [this.name]: [card].concat(prevState[this.name])
    }));
    

    演示:https://codesandbox.io/s/zrq0xxq2px

    它根据您的代码显示 2 个版本:

    • 修复了使用setState回调形式显示整个列表的版本
    • 基于您的代码的未修复版本,仅显示数组的最后一个元素

    来自官方React's documentation

    如果下一个状态依赖于前一个状态,我们建议使用 更新函数形式,而不是...

    【讨论】:

      猜你喜欢
      • 2022-12-09
      • 2020-04-15
      • 1970-01-01
      • 2020-09-29
      • 2012-11-13
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      相关资源
      最近更新 更多