微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

更新点 Redux React Native

如何解决更新点 Redux React Native

我正在尝试从 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;
  

解决方法

你的方法是正确的。问题实际上在于您尝试访问 ma​​pDispatchToProps 中的 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 }),};
};

如果您需要进一步的支持,请告诉我。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。