javascript - React/Redux:为什么我在this.props中的属性未定义?

我试图第一次在React中设置Redux,但似乎无法将初始状态从存储传递到组件。我的商店文件正在将状态设置为减速器的返回值。 Here is what happens when I log this.props to the console

零件



import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { exampleAction } from '../../actions';

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {}
  }

    render() {
      console.log(this.props)
      return (
        <div>
          <p>this is {this.props.examplePropOne}</p>
        </div>
      );
    } 
  }

  const mapStateToProps = state => ({
    examplePropOne: state.examplePropOne,
    examplePropTwo: state.examplePropTwo
  });

  const mapDispatchToProps = dispatch => {
    return bindActionCreators({ exampleAction }, dispatch)
  }

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





减速器



import { EXAMPLE_ACTION } from './../actions/types'

const initialState = {
  examplePropOne : 'Example Property One',
  examplePropTwo : 'Example Property Two'
}

export default function (state = initialState, action) {
  switch(action.type) {
    case EXAMPLE_ACTION: 
      return {
        ...state,
        examplePropOne: action.payload
      }
    default: 
      return state
  }
}





行动



import { EXAMPLE_ACTION } from './types'


export const exampleAction = text =>  ({
  type: EXAMPLE_ACTION,
  payload: text,
})





[编辑]

Here is what happens when I log the state within mapStateToProps



import React from 'react';
import { createStore, combineReducers } from 'redux';
import reducers from '../reducers';


export const store = createStore(
  combineReducers({
    state: reducers
  }),
);

最佳答案

通过将combineReducers()与作为键传递的state一起使用的方式,您的mapStateToProps()必须看起来像这样,才能访问examplePropOneexamplePropTwo

const mapStateToProps = state => ({
  examplePropOne: state.state.examplePropOne,
  examplePropTwo: state.state.examplePropTwo
});


鉴于 combineReducers()


  由combinedReducers()产生的状态为每个状态的名称空间命名
  传递给CombineReducers()的键下的reducer


问题是:

export const store = createStore(
  combineReducers({
    state: reducers
  }),
);


传递给 state的密钥 combineReducers()创建了 state的名称空间/属性。对于 state,使用名为 mapStateToProps()的参数时,要求将属性作为 state.state访问。可以通过改用传递给 combineReducers()的密钥一个更具描述性的名称来表示存储中用于管理的内容来解决此问题。例如,如果它与身份验证有关,则可以称为 auth之类的名称。它看起来像:

export const store = createStore(
  combineReducers({
    auth: reducers
  }),
);

// ...

const mapStateToProps = state => ({
  examplePropOne: state.auth.examplePropOne,
  examplePropTwo: state.auth.examplePropTwo
});


希望有帮助!