首页 > 解决方案 > 从 store 访问 state 和 props

问题描述

我刚刚开始,不知道如何从商店正确访问状态和道具。减速器代码是:

import {
    REQUEST_LINKS_PENDING,
    REQUEST_LINKS_SUCCESS,
    REQUEST_LINKS_FAILED
} from './selecttype_constants';

const initialState = {
    isPending: false,
    shelters: [],
    error: '',
};

export const selectShelter = (state=initialState, action) => {
    switch(action.type) {
        case REQUEST_LINKS_PENDING:
            return Object.assign({}, state, {isPending: true});
        case REQUEST_LINKS_SUCCESS:
            return Object.assign({}, state, {shelters: action.payload, isPending: false});
        case REQUEST_LINKS_FAILED:
            return Object.assign({}, state, {error: action.payload, isPending: false});
        default:
            return state;
    }
};

组件代码是

import React from 'react';
import { connect } from 'react-redux';

const mapStateToProps = (state) => {
    return {
        isPending: state.isPending,
        shelters: state.shelters,
    }
}

class SheltersList extends React.Component {

    render() {
        const { isPending, shelters} = this.props;
        if (isPending === false) {
            return (
                <div>
                    { shelters.map(function(shelter) {
                        <option id={shelter.id}>{shelter.name}</option>
                    })}
                </div>
            )
        } else {
            console.log('fetching')
            return (
            <option id='2'> Nahravam Data... </option>
        )}
    }
}

export default connect(mapStateToProps, null)(SheltersList);

访问isPending真/假状态和shelters数组以便将其映射到组件中的正确方法是什么?在“mapStateToProps should I usestate.isPending andstate.shelters to access the property the right way or should it bestate.selectShelter.isPending andstet.selectShelter.sheltersShelters.map ”? Cause in first case it never loads the shelters to the list and in second case I get an error I get an error that中不是一个函数。

标签: reactjs

解决方案


推荐阅读