React-Native/Redux 错误:请求的键值不是对象
2017-02-28
2074
在运行以下代码时,我在 CategoryList.js 中收到错误消息“请求的键的值不是对象”。
我相信 CategoryContainer.js 中的“stores.dispatch(CategoryAction.categoryView())”应该将值设置为 props 类别,但 CategoryList.js 中的 this.props.categories 返回空值,从而导致错误。
ConfigureStore.js:
import {createStore, applyMiddleware} from 'redux';
import reducers from '../reducers';
import thunk from 'redux-thunk';
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(reducers);
export default store;
CategoryContainer.js:
import React, { Component } from 'react';
import stores from '../stores/ConfigureStore';
import * as CategoryAction from '../actions/CategoryAction';
stores.dispatch(CategoryAction.categoryView());
class CategoryContainer extends Component {
render() {
return (
<CategoryList/>
);
}
}
const mapStateToProps = (state) => {
return {
categories: state.categories,
};
}
const mapDispatchToProps = (dispatch) => {
return {
bindActionCreators(CategoryAction, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CategoryContainer);
CategoryAction.js:
import * as actionTypes from './ActionTypes';
import AppConstants from '../constants/AppConstants';
export function categoryView() {
const categories = [{name:'CATEGORY', type:'CATGORY_TYPE'}];
return {
type: "CATEGORY_VIEW",
categories: categories
};
}
CategoryReducer.js:
const initialState = {
categories:[]
}
export default function categoryReducer (state = initialState, action) {
switch (action.type) {
case "CATEGORY_VIEW":
return Object.assign({}, state, {
categories: action.categories
});
}
}
CategoryList.js:
import React, {Component} from 'react';
import {
Text, View, TouchableHighlight, TouchableOpacity, ListView, StyleSheet
} from 'react-native';
import * as AppConstants from '../constants/AppConstants';
import CategoryAdd from '../components/CategoryAdd';
export default class CategoryList extends Component {
constructor(props) {
super(props);
this.ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2})
this.state = {
dataSource: this.ds.cloneWithRows(this.props.categories),
}
}
}
我甚至尝试过下面的 CategoryContainer.js 中,但它没有帮助。仍然有相同的错误,
<CategoryList {...this.props}/>
但如果我通过将 this.props.categories 替换为常量值来更改 CategoryList.js,如下所示,它就可以工作。
const categories = [{name:'CATEGORY', type:'CATGORY_TYPE'}];
this.state = {
dataSource: this.ds.cloneWithRows(categories),
}
请协助在 redux 流上设置 this.props.categories 中的值。
2个回答
您应该像这样更新 Reducer 中的
categories
数组 -
return Object.assign({}, state, {
categories: Object.assign([], state.categories, action.categories)
});
然后在容器中执行
<CategoryList {...this.props}/>
。
vinayr
2017-03-01
对 CategoryContainer.js 进行以下更改使其正常运行,
categories: state.categoryReducer.categories,
modal: state.categoryReducer.modal
ugendrang
2017-03-02