Redux mapStateToProps组件中的状态

时间:2019-05-20 08:31:16

标签: reactjs redux

我在Redux Dev Tools甚至是新状态中调用了我的动作,但是在实际的Component道具中是未定义的。

组件:

import React, { useEffect } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { getPromos } from '../../actions/promo';
import PropTypes from 'prop-types';

const Landing = ({ getPromos, data }) => {
  useEffect(() => {
    getPromos();
    console.log(data) // ==>> "UNDEFINED"
  }, []);

  return (
    <div>
      <section className='landing'>
        <div className='dark-overlay'>
          <div className='landing-inner'>
            <h1 className='x-large'> Developer Connector </h1>
            <p className='lead'>
              Create a developer profile/portfolio, share posts and get help
              from other developers
            </p>
            <div className='buttons'>
              <Link to='/register' className='btn btn-primary'>
                Sign Up
              </Link>
              <Link to='/login' className='btn btn-light'>
                Login
              </Link>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

Landing.propTypes = {
  getPromos: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  data: state.data
});

export default connect(
  mapStateToProps,
  { getPromos }
)(Landing);

操作:

import axios from 'axios';
import { setAlert } from './alert';
import { GET_PROMOS, REGISTER_FAIL } from './types';

export const getPromos = () => async dispatch => {
  try {
    const res = await axios.get('/api/promo');
    dispatch({
      type: GET_PROMOS,
      payload: res.data
    });
  } catch (err) {
    const errors = err.response.data.errors;
    if (errors) {
      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({ type: REGISTER_FAIL });
  }
};

和减速器:

import { GET_PROMOS } from '../actions/types';

const initialState = {
  data: null,
  title: ''
};

export default function(state = initialState, action) {
  const { type, payload } = action;

  switch (type) {
    case GET_PROMOS:
      return { ...state, data: payload };
    default:
      return state;
  }
}

就像我说的那样,在Redux Dev Tools中,我得到了想要的输出。但是由于某种原因,我无法在组件中回显此状态。我怎么了?可能是关于挂钩的事情吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

让我大吃一惊的是,您与组件中的getPromos存在命名冲突,它在导入中定义为getPromos,然后在组件中被解构为{ getPromos }也一样令您惊讶的是,您没有在那儿因为命名冲突而出错。 您将不希望在组件中破坏getPromos的结构,而是将其称为(props) => { props.getPromos }来实际调用连接的动作创建者而不是未连接的动作创建者。

第二,该减速器是主要的根减速器吗?还是嵌套在根减速器中?如果后者为true,则在您的mapStateToProps中,data道具应该更深一层,例如state: state.rootLevelState.data (抱歉,由于信誉<50而无法在评论中提问)

答案 1 :(得分:0)

enter image description here

这是redux开发工具的屏幕截图