首页 > 解决方案 > 如何使用 react 和 firebase 更新 CountJS 的值

问题描述

我在我的网络应用程序中使用 Firebase , Count js。这是我的代码。

import firebase from 'firebase';
import CountUp from 'react-countup';
const config = { ... }
class Stracture extends React.Component {
    constructor() {
        super()
        if (!firebase.apps.length) {
        firebase.initializeApp(config);
    }
    this.state = { balance: 0 };
}
componentDidMount() {
    firebase.database().ref('user1').child('balance').on('value', snap => {
        this.setState({ balance: snap.val()})
    });
}
render() {
    const { classes } = this.props;
    return (
        <CountUp className={classes.typo2} decimals={2} duration={1.5} end={this.state.balance} prefix="Balance: " suffix=" $" />
    )
};

我的代码工作正常。但现在我想使用更新功能从最近的值更新值。因为,当 Firebase 数据发生变化时,这个动画从 0..

标签: reactjsfirebasefirebase-realtime-database

解决方案


如果您想编写一个更新函数,则将 onClick 处理程序添加到CountUp指向新函数的组件。

<CountUp onClick={() => this.handleUpdate()} className={classes.typo2} decimals={2} duration={1.5} end={this.state.balance} prefix="Balance: " suffix=" $"  />

然后handleUpdate在类中创建函数并使其增加firebase中的余额值。

class Stracture extends React.Component {

  constructor() {...}

  componentDidMount() {...}

  handleUpdate = () => firebase.database().ref('user1').update({balance: this.state.balance + 1})

  render() {...}

}

更多关于更新如何工作的信息

您不需要更新状态,因为您已经有一个实时侦听器,因此一旦您更新了 firebase 中的值,更改将自动传播到您的应用程序。

如果您想传入一个值而不是加一,则将该值传递给 onClick 处理程序并将其作为参数接受到 handleUpdate 函数。

您可能应该记住的另外两件事包括处理更新函数的错误,因此您可以将其包装在 try/catch 块中并在 componentWillUnmount 中分离实时侦听器。


推荐阅读