简体   繁体   中英

showing response from reddit api in react-redux app

I am making a call to the reddit api from a react-redux app. The response is coming from reddit and contains all the data. It returns 25 posts, of which i am only able to show one on the front end. I believe it is because it is a nested array.

Can anyone see anything that I am doing incorrectly?

Please see jsfiddle here.

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers } from 'redux';
import { connect, Provider } from 'react-redux';
import axios from 'axios';


function addData(state = [], action) {
    switch(action.type) {
        case 'ADD_DATA':
            var newState = state.concat([action.data]);
            return newState
        default:
            return state;
    }
    return state;
}

const store = createStore(addData);

class App extends React.Component {

    componentDidMount() {
        axios.get('https://www.reddit.com/r/reactjs/.json').then(response => {
            var response = response.data.data.children;
            store.dispatch({
                type: 'ADD_DATA',
                data: response
            });
            console.log('Response Returned Now');
        })      
    }

    render() {
        var list = this.props.data.map(function(item, i){
            return (<li key={i}>{item[i].data.title}</li>)
        })
        return (
            <ul>
                {list}
            </ul>
        )
    }
}

const mapStateToProps = function(store){
    return {
        data: store
    }
}

const ConnectedApp = connect(mapStateToProps)(App);
ReactDOM.render(
  <Provider store={store}>
    <ConnectedApp />
  </Provider>
    , document.getElementById('app')
);

The returned response is already an array. In your reducer, when you did state.concat([action.data]) it returns a nested array [Array[25]]

use state.concat(action.data) then replace your var list to this.props.data.map(function(item, i) { return (<li key={i}>{item.data.title}</li>) })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM