我有一个高阶函数,并且在其中试图访问存储在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全局状态。
更新:减速器代码
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
答案 0 :(得分: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;
}
};
答案 1 :(得分:0)
我不确定您是否可以像示例中那样连接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
应该没有任何问题。