问题描述
我正在尝试从 Firebase 加载点以将其显示在屏幕上
我正在使用 Redux,因为点数可以更新,但我不能把 this.props.Points.updatePoint
放在 Firebase 请求中
如何更新?
Home.js
:
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount = async () => {
const pointsRef=firebase.database().ref("Users").child(firebase.auth().currentUser.uid).orderByChild("Points").once('value',function(snapshot){
const Points=snapshot.val().Points
});
this.props.Points.updatePoints(Points)
render(){
return(
<Text>{this.props.Points}</Text>
)}
}
const mapStatetoProps = (state) => {
return {
Points:state.Points};
};
const mapdispatchToProps = (dispatch) => {
return {
updatePoints:(Points)=>dispatch({ type: "UPDATE_POINTS",payload: Points }),};
};
PointReducer.js
:
const initialState = {
Points: 0,};
const Points = (state = initialState,action) => {
switch (action.type) {
case "UPDATE_POINTS":
return {
...state,Points: action.payload,};
default:
return state;
}
};
export default Points;
解决方法
你的方法是正确的。问题实际上在于您尝试访问 mapDispatchToProps 中的 updatePoints
函数的方式以及您运行语句的位置。
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount = async () => {
const pointsRef = firebase
.database()
.ref("Users")
.child(firebase.auth().currentUser.uid)
.orderByChild("Points")
.once("value",(snapshot) => {
const Points = snapshot.val().Points;
this.props.updatePoints(Points); // You can directly access to `updatePoints` using prop object.
}); // convert this function to an arrow function. It will fix `this` related issues.
};
render() {
return <Text>{this.props.Points}</Text>;
}
}
const mapStateToProps = (state) => {
return {
Points: state.Points,};
};
const mapDispatchToProps = (dispatch) => {
return {
updatePoints: (Points) =>
dispatch({ type: "UPDATE_POINTS",payload: Points }),};
};
如果您需要进一步的支持,请告诉我。