【问题标题】:Update points Redux React Native更新点 Redux React Native
【发布时间】:2021-08-23 06:10:51
【问题描述】:

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

【问题讨论】:

    标签: react-native redux react-redux reducers redux-reducers


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-07
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      相关资源
      最近更新 更多