无法获得更新的道具/州

时间:2018-03-28 03:58:39

标签: firebase react-native redux components redux-thunk

在我的动作课中,我有一个方法如下

export const userSettingFetch = () => {
  const { currentUser } = firebase.auth();

  return (dispatch) => {
    firebase.database().ref(`/users/${currentUser.uid}/userSettings`)
      .on('value', snapshot => {

        dispatch({ type: USER_SETTING_FETCH_SUCCESS, payload: snapshot.val()});
      });
  };
};

调用上述方法后,它将调度到UserSettingReducer reducer,并存储到userSettingData状态,定义如下:

const INITIAL_STATE = {
  userSetting_DailyLimit: '',
  userSetting_City: '',
  userSetting_DisplayName: '',
  userSettingData: null
};
export default (state = INITIAL_STATE, action) => {
  console.log(action);
  switch (action.type) {
    case USER_SETTING_UPDATE:
      return { ...state, [action.payload.prop]: action.payload.value };
    case USER_SETTING_SUBMISSION_SUCCESS:
      return state;
    case USER_SETTING_FETCH_SUCCESS:
      return { ...state, userSettingData: action.payload };//action.payload;
    default:
      return state;
  }
};

以下是我的combineReducers代码:

export default combineReducers({
  auth: AuthReducer,
  userSetting: UserSettingReducer
});

现在来到我的组件如下;

class MainScreen extends Component {
  componentWillMount() {
    console.log('inside MainScreen componentWillMount method');
    this.props.userSettingFetch();
    //console.log('Name is: '+this.props.userSettingData.userSetting_DisplayName);
  }
  render() {
    return(
      <Text>{this.props.userSettingData.userSetting_DisplayName}</Text>
    );
  }
}

const mapStateToProps = ({ auth, userSetting }) => {
  const { email, password, error, loading } = auth;
  const { userSettingData } = userSetting;

  return { email, password, error, loading, userSettingData };
};

export default connect(mapStateToProps,{ userSettingFetch })(MainScreen);

以下是应用程序运行时的控制台日志:

enter image description here

对我来说,一切看起来都很完美,但我有异常说userSettingData未定义?

2 个答案:

答案 0 :(得分:1)

在INITIAL_STATE中,userSettingData为null,您尝试访问userSettingData的{​​{1}}属性。你可以在那里检查 -

{this.props.userSettingData 
  ? <Text>{this.props.userSettingData.userSetting_DisplayName}</Text> 
  : <Text>User setting data still not available</Text>
}

或者您可以将userSettingData初始化为空对象

您的有效负载是一个具有随机密钥的对象,您想要的对象是该密钥的值。要从那里获取对象,您可以使用Object.entries -

payload: Object.entries(snapshot.val())[1]

答案 1 :(得分:0)

INITIAL_STATE API调用之前,您的userSettingData似乎未包含userSettingFetch对象。因此,您userSettingDataundefined。其中一个选项是显示微调器,直到状态userSettingData可用,但它需要对您的应用程序进行其他更改。

当你破坏不包含mapStateToProps密钥的对象userSetting时,另一种情况可能是userSettingData