我正在使用react-redux应用程序调用reddit api。响应来自reddit并包含所有数据。它返回25个帖子,其中我只能在前端显示一个。我相信这是因为它是一个嵌套数组。
任何人都可以看到我做错的事吗?
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')
);
答案 0 :(得分:1)
返回的response
已经是一个数组。在您的reducer中,当您执行state.concat([action.data])
时,它返回一个嵌套数组[Array[25]]
使用state.concat(action.data)
,然后将var list
替换为this.props.data.map(function(item, i) { return (<li key={i}>{item.data.title}</li>) })