【发布时间】:2019-04-28 02:19:37
【问题描述】:
我只是想在我的 React 应用程序中集成一个新的 Container,将它与 Redux 连接起来,只是想看看它是否能正常工作。然而并非如此。通过this.props.selection 访问reducer 给了我undefined。我不知道为什么。它确实可以在其他容器中工作,并且 reducer 具有一些明确定义的初始状态。 - 我不确定我看到这里有什么区别?我错过了一些琐碎的事情吗?
import React, { Component } from 'react'
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
export class AudioPlayer extends Component {
constructor(props) {
super(props);
this.state = { someComponentState : true }
}
onLog() {
console.log("Logging:");
console.log(this.props.selection); // gives me: undefined
}
render() {
return (
<div>
<button onClick={()=> this.onLog()}>LOG</button>
</div>
)
}
}
function mapStateToProps (state) {
return {
selection: state.selection
};
}
export default connect(mapStateToProps)(AudioPlayer);
PS:我已经稍微简化了这个组件,但我认为它仍然应该反映问题。
编辑:reducer 示例 人们要求查看减速器,但是,我已经尝试了几个已经在应用程序中实现并在其他容器中工作的减速器,所以我认为这不是问题所在 - 但谁知道:
import { SELECT_ITEM } from '../actions/types';
export default function(state = {}, action) {
switch(action.type) {
case SELECT_ITEM:
return {...state, error:'', selected: true};
}
return state;
}
edit2:mapStateToProps 似乎根本没有被调用 我只是尝试在 mapStateToProps 中做一个 console.log,看看它是否被调用,似乎从来没有。没有任何记录。这可能是什么原因?
function mapStateToProps (state) {
console.log("In map function");
console.log(state);
return {
selection: state.selection, //both return
auth: state.auth // undefined
};
}
我还添加了另一个 reducer (auth),它可以在应用程序的其他地方工作,但这里返回 undefined。
edit3:我的根减速器
import { combineReducers } from 'redux';
import { reducer as form } from 'redux-form';
//reducer imports
import authReducer from './auth_reducer';
import articlesReducer from './articles_reducer';
import userReducer from './user_reducer';
import currentSelectionReducer from './currentSelection_reducer';
const rootReducer = combineReducers({
auth: authReducer,
user: userReducer,
articles: articlesReducer,
selection: currentSelectionReducer,
});
export default rootReducer;
【问题讨论】:
-
你能显示设置
initialState的代码吗? -
我已经在应用程序中实现了几个减速器并且已经在使用这些减速器。所以如果问题出在reducer代码本身就会很奇怪。当然,我可以添加它。
-
是的,从代码中,我觉得
state.selection是未定义的,因此您将this.props.selection视为未定义 -
是的,看起来就是这样,但我在应用程序的其他地方成功访问它并将其初始化为空对象。哦,还有一点很有趣的是,无论我使用哪个减速器(我的应用程序有多个),它总是在那个组件中给我 undefined,而在其他组件中它很好。
-
嗯,您提供的减速器适用于
selected字段。您在哪个 reducer 中管理selection字段?
标签: javascript reactjs redux react-redux flux