首页 > 解决方案 > TypeError:无法读取未定义的 mapStateToProps 的属性

问题描述

将组件链接到商店时遇到错误。

TypeError:无法读取未定义的属性“errorMessage”

Function.mapStateToProps [as mapToProps]

  37 | const mapStateToProps = (state: AppState) => ({
> 38 |   errorMessage: state.errorRedux.errorMessage,
  39 |   error: state.errorRedux.error,
  40 | })

我无法指出问题所在。它不应该监听错误,因为我选择有条件地呈现消息。

  1. 我试过设置errorMessage: string | undefined | null没有成功。
  2. 我试过errorMessage: "[INTERFACE"]没有成功。
  3. 我试过errorMessage?: string 了,我认为问题可能出在扩展 ErrorHandlerProps 接口的某个地方,但我已经扩展了 mapStateToProps?
import { Dispatch, Action } from "redux"
import { connect } from "react-redux"
import { AppState } from "reducers"
import { showError } from "data/error_handler"

class ErrorHandler extends React.Component<
  ReturnType<typeof mapStateToProps> & ReturnType<typeof mapDispatchToProps>
> {
  public render() {
    const { onShowError, error, errorMessage } = this.props

    let showTheError =
      this.props.error === true ? (
        <Snackbar
          open={error}
          message={errorMessage}
          autoHideDuration={5000}
        />
      ) : null

    return (
      <div>
        <RaisedButton onClick={onShowError} label="Toggle ErrorHandler" />
        {showTheError}
      </div>
    )
  }
}

const mapStateToProps = (state: AppState) => ({
  errorMessage: state.errorRedux.errorMessage,
  error: state.errorRedux.error,
})

const mapDispatchToProps = (dispatch: Dispatch<Action>) => {
  return {
    onShowError: () => dispatch(showError()),
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ErrorHandler)

data/interfaces.ts

export interface ErrorHandlerProps {
  error: boolean
  errorMessage: string
}

data/reducer.ts

import { ErrorHandlerProps, ActionTypes } from "./"

const initialState: ErrorHandlerProps = {
  error: false,
  errorMessage: "",
}

export default (
  state: ErrorHandlerProps = initialState,
  action: ActionTypes
) => {
  switch (action.type) {
    case "SHOW_ERROR":
      return {
        ...state,
      }
    default:
      return state
  }
}

reducers.ts

import { reducer as errorHandler, ErrorHandlerProps } from "data/error_handler"

const appReducer = combineReducers({
  errorHandler
} as any)

export type AppState = {
  errorRedux: ErrorHandlerProps
}

store.ts

import { createStore, applyMiddleware, compose } from "redux"
import { routerMiddleware } from "react-router-redux"
import thunk from "redux-thunk"
import rootReducer, { AppState } from "reducers"

const initialState = {}
const middleware = [thunk, routerMiddleware(history)]
const composedEnhancers = compose(applyMiddleware(...middleware), ...enhancers)
const store = createStore(rootReducer, initialState, composedEnhancers)

export default store
export const getState = () => store.getState() as AppState

标签: reactjstypescriptreduxreact-redux

解决方案


如果我们能看到您是如何创建商店的,那就更容易了。

通常,当您使用 时会发生此问题combineReducers,因为它创建了一个 reducers 对象,而这就是mapStateToProps接收的对象,而不是直接接收状态。

import { createStore, combineReducers } from "redux";
import testReducer from "./reducer";
import testReducer2 from "./reducer2";

// ----
// using combine reducers will make the state in mapStateToProps to be an object of all the reducers combined, so you have to access it like state.testReducer.value or state.testReducer2.value

const rootReducer = combineReducers({
  testReducer,
  testReducer2
});
// ----

// ----
// while passing a reducer directly will not have the same effect and the state will be accessible like state.value in mapStateToProps

const rootReducer = testReducer;
// ----

const store = createStore(rootReducer);

export default store;

请参阅以下沙箱:https ://codesandbox.io/s/k3ojkqxy57


推荐阅读