TypeError:无法读取未定义的React Native Redux的属性'map'

时间:2018-09-03 12:11:45

标签: reactjs react-native redux reducers

我试图按照我使用git repos的示例相同的逻辑创建一个reducer

这里是减速器:

/**
 * Created by kenji on 3/9/18.
 */
/**
 * /stock?search=String
 * Searches Stock table, checking for given search value
 * and returns an array that contains that value
 * @action GET
 * @returns [array]
 * @type {string}
 */
export const GET_STOCK_LIST = 'ReduxStarter/stock_list/LOAD';
export const GET_STOCK_LIST_SUCCESS = 'ReduxStarter/stock_list/LOAD_SUCCESS';
export const GET_STOCK_LIST_FAIL = 'ReduxStarter/stock_list/LOAD_FAILURE';

/**
 * /stock/${id}
 * Gets an ID passed to it and returns an object if it exists
 * @action GET
 * @returns {object}
 * @type {string}
 */
export const GET_STOCK = 'ReduxStarter/stock/LOAD';
export const GET_STOCK_SUCCESS = 'ReduxStarter/stock/LOAD_SUCCESS';
export const GET_STOCK_FAIL = 'ReduxStarter/stock/LOAD_FAIL';

/**
 * /stock/${id}
 * Updates Stock by passing an object with new variables to update with
 * @action PUT
 * @returns {null}
 * @type {string}
 */
export const PUT_STOCK = 'ReduxStarter/stock/CHANGE';
export const PUT_STOCK_SUCCESS = 'ReduxStarter/stock/CHANGE_SUCCESS';
export const PUT_STOCK_FAIL = 'ReduxStarter/stock/CHANGE_FAIL';

/**
 * /stock/${id}/barcodes
 * Gets the barcodes of an a stock item if the ID is valid
 * @action: GET
 * @returns [array]
 * @type {string}
 */
export const GET_BARCODES = 'ReduxStarter/stock/barcodes/LOAD';
export const GET_BARCODES_SUCCESS = 'ReduxStarter/stock/barcodes/LOAD_SUCCESS';
export const GET_BARCODES_FAIL = 'ReduxStarter/stock/barcodes/LOAD_FAIL';

/**
 * /stock/barcode/${barcode}
 * Gets a stock item from the supplied barcode
 * @action: GET
 * @returns [array]
 * @type {string}
 */
export const GET_STOCK_FROM_BARCODE = 'ReduxStarter/stock/barcode/LOAD';
export const GET_STOCK_FROM_BARCODE_SUCCESS = 'ReduxStarter/stock/barcode/LOAD_SUCCESS';
export const GET_STOCK_FROM_BARCODE_FAIL = 'ReduxStarter/stock/barcode/LOAD_FAIL';

const initialState = {
    stockList: [],
    stock: {},
    result: {},
    barcodeList: [],
    stockFromBarcode: {},
};

export default function reducer(state = initialState, action) {
    switch(action.type) {
        case GET_STOCK_LIST:
            return { ...state, loadingStockList: true };
        case GET_STOCK_LIST_SUCCESS:
            return { ...state, loadingStockList: false, stockList: action.payload.data };
        case GET_STOCK_LIST_FAIL:
            return { ...state, loadingStockList: false, stockListError: 'Failed to retrieve stock list' };
        case GET_STOCK:
            return { ...state, loadingStock: true };
        case GET_STOCK_SUCCESS:
            return { ...state, loadingStock: false, stock: action.payload.data };
        case GET_STOCK_FAIL:
            return { ...state, loadingStock: false, stockError: 'Failed to retrieve stock list' };
        case PUT_STOCK:
            return { ...state, loadingStockUpdate: true };
        case PUT_STOCK_SUCCESS:
            return { ...state, loadingStockUpdate: false, result: action.payload.data };
        case PUT_STOCK_FAIL:
            return { ...state, loadingStockUpdate: false, stockUpdateError: 'Failed to update stock list' };
        case GET_BARCODES:
            return { ...state, loadingBarcodes: true };
        case GET_BARCODES_SUCCESS:
            return { ...state, loadingBarcodes: false, barcodeList: action.payload.data };
        case GET_BARCODES_FAIL:
            return { ...state, loadingBarcodes:false, barcodesError: 'Failed to load barcodes' };
        case GET_STOCK_FROM_BARCODE:
            return { ...state, loadingStockFromBarcode: true };
        case GET_STOCK_FROM_BARCODE_SUCCESS:
            return { ...state, loadingStockFromBarcode: false, stockFromBarcode: action.payload.data };
        case GET_STOCK_FROM_BARCODE_FAIL:
            return { ...state, loadingStockFromBarcode: false, stockFromBarcodeError: 'Failed to get stock item from barcode' };
        default:
            return state;
    }
}

export function listStockArray(searchQuery, pageSize = 50, pageNumber = 1) {
    return {
        type: GET_STOCK_LIST,
        payload: {
            request: {
                url: `/stock?search=${searchQuery}&pageSize=${pageSize}&pageNumber=${pageNumber}`
            }
        }
    };
}

export function listStockItem(stockID) {
    return {
        type: GET_STOCK_LIST,
        payload: {
            request: {
                url: `/stock/${stockID}`
            }
        }
    };
}

export function updateStock(stockID, data) {
    return {
        type: GET_STOCK_LIST,
        payload: {
            request: {
                url: `/stock/${stockID}`,
                method: `PUT`,
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                data: data,
            }
        }
    };
}

export function listStockBarcodes(stockID) {
    return {
        type: GET_BARCODES,
        payload: {
            request: {
                url: `/stock/${stockID}/barcodes`
            }
        }
    };
}

export function listStockFromBarcode(barcode) {
    return {
        type: GET_BARCODES,
        payload: {
            request: {
                url: `/stock/barcode/${barcode}`
            }
        }
    };
}

现在我得到标题中提到的错误: ** TypeError:无法读取未定义的属性“地图” **

以下是减速器对应用程序的暗示:

import reducers from './redux/reducers/lots_reducer';
import StockList from './components/StockList';

const client = axios.create({
    baseURL: 'https://api.github.com',
    responseType: 'json'
});

const store = createStore(reducers, applyMiddleware(axiosMiddleware(client)));

const Stack = createStackNavigator({
    StockList: {
        screen: StockList
    },
});

export default class App extends Component {
    render() {
        return (
            <Provider store={store}>
                <View style={styles.container}>
                    <Stack/>
                </View>
            </Provider>
        );
    }
}

最后是实际组件:

import { connect } from 'react-redux';

import { listStockArray } from '../redux/reducers/lots_reducer';

class StockList extends Component {

    componentDidMount() {
        this.props.listStockArray('panadol');
    }

    renderItem = ({ stockList }) => (
        <TouchableOpacity
            style={styles.item}
            onPress={() => this.props.navigation.navigate(`Detail`, { name: stockList.StockID })}
        >
            <Text>{stockList.TradeName}</Text>
        </TouchableOpacity>
    );

    render() {
        const { stockList } = this.props;
        return (
            <FlatList
                styles={styles.container}
                data={stockList}
                renderItem={this.renderItem}
            />
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    item: {
        padding: 16,
        borderBottomWidth: 1,
        borderBottomColor: '#ccc'
    }
});

const mapStateToProps = state => {
    let storedRepositories = state.repos.map(repo => ({ key: (repo.id).toString(), ...repo }));
    return {
        repos: storedRepositories
    };
};

const mapDispatchToProps = {
    listStockArray
};

export default connect(mapStateToProps, mapDispatchToProps)(StockList);

很抱歉,转储了大量代码,所有代码都与之相关,我相信错误在于某处未定义的initialState内,但我看不到我错过的定义

3 个答案:

答案 0 :(得分:1)

此代码

const mapStateToProps = state => {
    let storedRepositories = state.repos.map(repo => ({ key: (repo.id).toString(), ...repo }));
    return {
        repos: storedRepositories
    };
};

表示要转换(将id更改为key属性)state.repos,使用map函数,并使用中间变量repos作为storedRepositories返回。这些部分看起来像原始的,而不是从回购示例中更改的。

由于状态不包含repos数组而出现错误。您还有其他几个状态数组(reducer中的initialState),但是它们都不是repos

在reducer中,您将有效载荷(获取的数据)存储在存储数组中,例如

    case GET_STOCK_LIST_SUCCESS:
        return { ...state, loadingStockList: false, stockList: action.payload.data };

将数据存储在stockList中。对于其他成功操作,您还有其他数组名称。

组件不必使用所有存储数据,您可以仅使用其感兴趣的部分-这是进行mapStateToProps映射的原因。您可以像

一样简单
const mapStateToProps = state => {
    return {
        stockList: state.stockList, 
        stock: state.stock
    };
};

这些值将以this.props.stockListthis.props.stock的形式提供。

答案 1 :(得分:0)

好像您没有定义repos一样,您如何映射它?

const initialState = {
  stockList: [],
  stock: {},
  result: {},
  barcodeList: [],
  stockFromBarcode: {},
  repos: []
};

或者,您的意思是另一个领域。

答案 2 :(得分:0)

因为您尝试使用map函数,该函数可用于数组,而您repo不能用于数组。 当您repo时,mapping可能不是(可能在分配值之前)。

方法:我只是使用Array.isArray()检查它在哪里,如果Array则可能返回空数组。

如@sagi所述,更好的方法是使用repo字段将您的状态初始化为空数组。基本上,当

  

您尝试将数组函数用于非数组元素