【问题标题】:I can only parse my mapStateToProps object to an extent inside of my react component我只能在我的反应组件内部解析我的 mapStateToProps 对象
【发布时间】:2018-10-05 19:37:10
【问题描述】:

当我在我的 react 组件中 mapStateToProps 时,我对 redux 还很陌生,并且无法解析 JSON 数据。例如,如果我在我的 react 组件中使用 console.log(this.props.chartData[0]),控制台将显示我尝试访问的数组,但是,当我尝试通过控制台访问数组中的特定元素时记录(this.props.ChartData[0].title),我得到一个错误:

[enter image description here][1]



class ChartContainer extends Component {

    componentWillMount(){
        this.props.chartChanged();
    }

    render(){
        console.log(this.props.chartData[0]);
        return(
            <Text style={styles.textStyle}>
                test
            </Text>   
        );
    }
}



const mapStateToProps = state => {
    return {
        chartData: state.chart
    }
};


export default connect (mapStateToProps, {chartChanged}) (ChartContainer);

有趣的是,我在 reducer 中访问(this.props.ChartData[0].title) 没有问题。

import {CHART_CHANGED} from '../actions/types';

const INITIAL_STATE = { chartData: [] };

export default (state = INITIAL_STATE, action) => {
        console.log(action);

 switch (action.type) {
        case CHART_CHANGED:
            console.log("action");
            console.log(action.payload[0].title);
            return{...state, chartData: action.payload};
        default: 
            return state;
    }
};

这是我的操作文件中的 api 调用:

export const chartChanged = (chartData) => {

return (dispatch) => {
    axios.get('https://rallycoding.herokuapp.com/api/music_albums')
        .then((chartData) =>{
            dispatch({type: CHART_CHANGED, payload: chartData.data});
        });
    };
};

如果有人能解释为什么会发生这种情况,我将非常感激。

【问题讨论】:

  • 它是否记录了一个空数组?
  • 不,它正在记录未定义。
  • 您是从 API 获取数据吗?
  • 是的,我从 API 获取。
  • 你能给我看看这个console.log this.props.ChartData吗?

标签: react-native redux axios redux-thunk


【解决方案1】:

所以问题是你不应该在获取过程中分配任何值,你需要做的是使用 lodash 并尝试做这样的事情

import _ from 'lodash'

const title = _.get(this.props.ChartData, 'chartData', [])

if(!isFetching){
//do something
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 2019-03-07
    • 2017-09-01
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多