【问题标题】:Higher Order Functions Unable to Access Redux State高阶函数无法访问 Redux 状态
【发布时间】:2019-09-22 21:17:36
【问题描述】:

我有一个高阶函数,在里面我试图访问存储在 Redux 中的状态属性“isAuthenticated”。出于某种原因,它说状态是未定义的。

import React,{ Component } from 'react';
import { connect } from 'react-redux'

export default function(ComposedComponent) {

    class Authenticate extends Component {

        render() {

            return (
                <ComposedComponent {...this.props} />
            )
        }
    }

    const mapStateToProps = (state) => {
        return {
            isAuthenticated: state.isAuthenticated
        }
    }


    return connect(mapStateToProps)(Authenticate)
}

更新:

我像这样使用高阶组件:

ReactDOM.render(
<Provider store = {store}>
  <BrowserRouter>
    <BaseLayout>
    <Switch>
      <Route path='/' exact component={App} />
      <Route path='/profile' component={requireAuth(Profile)} />
    </Switch>
    </BaseLayout>
  </BrowserRouter>
</Provider>
  , document.getElementById('root'));

我已经检查并且 redux 状态已正确初始化,因为我在订单页面中使用它。我在阻止它访问 redux 全局状态的高阶函数中缺少什么。

更新:reducer 代码

const initialState = {
  isAuthenticated: false
}

const reducer = (state = initialState, action) => {
  switch(action.type) {
    case 'AUTHENTICATED':
      return {
        ...state,
        isAuthenticated: action.value != null ? true : false 
      }
  }
}

export default reducer

【问题讨论】:

  • 你使用 combineReducers 以及你如何使用你的 HOC
  • 不!我只有一个减速器。
  • 您收到的错误是什么,它指向哪里,因为您的代码似乎是正确的
  • 我用截图更新了问题。
  • 减速器里有什么?也许它与这个问题相同:stackoverflow.com/questions/38976134/… 你需要 return state 作为默认值

标签: reactjs redux


【解决方案1】:

您在 reducer => 初始时缺少默认返回,当您不发送操作“AUTHENTICATED”时,您的商店为undefined

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "AUTHENTICATED":
      return {
        ...state,
        isAuthenticated: action.value != null ? true : false
      };
    default:
      return initialState;
  }
};

【讨论】:

  • 你应该return state 而不是initialState 否则,每次通过这个reducer时它都会将redux状态重置为其初始状态而没有action.type == 'AUTHENTICATED'
【解决方案2】:

我不确定您是否可以像您的示例中那样设法连接mapStateToProps。相反,我会导入ComposedComponent 并使用redux 连接Authenticate

import React,{ Component } from 'react';
import { connect } from 'react-redux'
import ComposedComponent from './PATH_TO/ComposedComponent'

class Authenticate extends Component {

  render() {

    return (
      <ComposedComponent {...this.props} />
     )
  }
}

const mapStateToProps = (state) => {
  return {
    isAuthenticated: state.isAuthenticated
  }
}

export default connect(mapStateToProps)(Authenticate)

现在您从商店访问isAuthenticated 应该没有任何问题。

【讨论】:

  • 我不能使用这种方法,因为我需要更高阶的组件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 2019-03-24
  • 2020-07-15
  • 1970-01-01
  • 2023-03-23
  • 2020-10-26
  • 1970-01-01
相关资源
最近更新 更多