【问题标题】:mapStateToProps not assigning state to props - react-native/redux/firebase,mapStateToProps 未将状态分配给道具 - react-native/redux/firebase,
【发布时间】:2019-09-20 02:56:07
【问题描述】:

我在 mapStateToProps 函数中接收到我的 redux 状态,但该状态没有映射到道具,因此在我的组件中不可用。

我在 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;

【问题讨论】:

    标签: firebase react-native redux react-redux


    【解决方案1】:

    你的 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 
        }
    }
    

    【讨论】:

      【解决方案2】:

      感谢 Malik 的回答,我意识到我的问题出在我调用 console.log 的地方。 ComponentDidMount 函数正确地将状态分配给 props,但是,它只能在 render() 函数中访问……一旦组件安装和渲染,props 就可以使用了。

      希望这对人们有所帮助!

      【讨论】:

        猜你喜欢
        • 2020-07-15
        • 1970-01-01
        • 2017-11-07
        • 2017-05-17
        • 2018-02-03
        • 1970-01-01
        • 1970-01-01
        • 2016-09-19
        • 1970-01-01
        相关资源
        最近更新 更多