mapStateToProps没有为道具分配状态-react-native / redux / firebase,

时间:2019-05-01 14:40:51

标签: firebase react-native redux react-redux

我在mapStateToProps函数中接收到我的redux状态,但是该状态未映射到props,因此无法在我的组件中使用。

我已经在mapStateToProps函数中运行console.log并收到了数据。道具未分配状态对象/阵列(console.log中有一个返回的阵列)。

帮助!

我的组件:

componentDidMount() {
        this.props.onLoadHabits();
        console.log(this.props.habits)
        // undefined
    }

const mapStateToProps = state => {
    console.log(state.habits.habits)
    // returns an array with my two test objects included... [ Object, Object]
    return {
        habits: state.habits.habits
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onLoadHabits: () => dispatch(getHabits())
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(RoutineScreen);

我的动作:

export const getHabits = () => {
    return dispatch => {
        fetch("https://bestlyfe-b368a.firebaseio.com/habits.json")
            .catch(err => {
                console.log(err);
                alert('Something went wrong, sorry :(');
            })
            .then(res => res.json())
            .then(parsedRes => {
                const habits = [];
                for (let key in parsedRes) {
                    habits.push({
                        ...parsedRes[key],
                        key: key
                    })
                }
                console.log(habits);
                dispatch(setHabits(habits));
            })
    }
}

export const setHabits = habits => {
    return {
        type: SET_HABITS,
        habits: habits
    }
}

我的减速机

const habitsReducer = (state = initialState, action) => {
  switch (action.type) {
  case SET_HABITS:
      return {
        ...state,
        habits: action.habits
      }
 default:
      return state;
  }
};

export default habitsReducer;

2 个答案:

答案 0 :(得分:0)

您的mapStateToProps错误。将您的mapStateToProps更改为以下

const mapStateToProps = state => {
    console.log(state.habits.habits)
    // returns an array with my two test objects included... [ Object, Object]
    return {
        //Change state.habits.habits to state.habitsReducer 
        habits: state.habitsReducer 
    }
}

答案 1 :(得分:0)

感谢Malik的回答,我意识到我遇到的问题是我在哪里调用console.log。 ComponentDidMount函数已将状态正确分配给道具,但是,只能在render()函数中访问该状态...一旦安装并渲染了组件,即可使用道具。

希望这对人们有帮助!