reactjs - 如何使用 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..
解决方案
如果您想编写一个更新函数,则将 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 中分离实时侦听器。
推荐阅读
- apache-nifi - 如何在nifi中解析mysql json列
- java - 如果使用双变量实例化 LatLng 对象将不起作用,它仅在输入实数时才起作用
- reactjs - 构建时,isolatedModules 设置为 true,导致错误:无法使用选项 'isolatedModules' 指定选项 'noEmitOnError'
- neo4j - 如何在不提供节点 ID 的情况下在 neo4j 中快速创建节点?
- r - 自动化(手动)R 代码以计算 P 值
- cplex - 如何使用模型中的解决方案来解决另一个问题
- autodesk-forge - 使用 Forge API 读取 REVIT 文件中的族
- javafx - 从控制器类外部调用的 gridpane.getchildren().add() 会阻止程序
- c# - 如何检测 TrailRenderer 创建的闭环,然后在里面获取游戏对象
- javascript - 如何在动态选择组件角度中设置选择默认值