我想将ImmutableJS合并到我的React应用程序中,所以现在我的reducer看起来像这样:
import { Map } from 'immutable'
const initialState = Map({
data: [],
sections: []
});
const AppState = (state = initialState, action) => {
switch (action.type) {
case 'ADD_CONTENT':
return state.set('data', action.response);
case 'ADD_SECTION':
return state.set('sections', [ ...state.get('sections'), action.payload ]);
default:
return state;
}
};
export default AppState;
这一切都很好。但是在我的组件中,我有mapStateToProps
:
const mapStateToProps = (state) => {
const d = state.app.get('data');
return {
works: d.works,
pages: d.pages,
sections: state.app.get('sections')
}
};
然后我想显示数据:
{
this.props.works.map(d => {
return <div>d</div>
})
}
我得到
TypeError: this.props.works.map is not a function
当我替换console.log
时,我得到this.props.works
没有定义。我能做什么?
因为你使用的是不可变JS
在你的mapStateToProps
const mapStateToProps = (state) => {
const d = state.app.get('data');
return {
works: d.works,
...
从d
访问数据,改变访问方式,从d.works
到 d.get('works')
return {
works: d.get('works'),
pages: d.get('pages'),
sections: state.app.get('sections')
}
您正在调用d.s works,但它尚未定义。我认为在你的操作中当你传入初始状态时你还需要定义works
const initialState = Map({
data: [
works: [],
pages: []
],
sections: []
});