首页 > 解决方案 > React/Redux:为什么我在 this.props 中的属性未定义?

问题描述

我第一次尝试在 React 中设置 Redux,但我似乎无法将初始状态从商店传递到组件。我的商店文件将状态设置为减速器的返回值。这是我将 this.props 记录到控制台时发生的情况

零件

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,
})

[编辑]

这是我在 mapStateToProps 中记录状态时发生的情况

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


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

标签: javascriptreactjsreduxreact-redux

解决方案


使用 how combineReducers()is used withstate作为键传入,您mapStateToProps()需要看起来像这样才能访问examplePropOneand examplePropTwo

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

鉴于combineReducers()

combineReducers() 产生的状态命名空间将每个 reducer 的状态在其键下传递给 combineReducers()

问题是:

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

state传递给的键combineReducers()创建了一个命名空间/属性state。使用为 命名的参数statemapStateToProps()要求将属性作为 访问state.state。这可能可以通过将传递的密钥提供给combineReducers()一个更具描述性的名称来解决,该名称表示商店中用于管理的内容。例如,如果它与身份验证有关,则可以将其称为auth. 它看起来像:

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

// ...

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

希望这会有所帮助!


推荐阅读