【发布时间】:2018-05-01 10:36:16
【问题描述】:
所以我正在做的事情如下:
一个动作从一个 url 获取一个 .json 文件并调度另一个动作。 pilots 的值为 [Array(278)]。
export const pilotsFetchDataSucces = (pilots) => {
return {
type: 'PILOTS_FETCH_DATA_SUCCES',
pilots
}
};
export const pilotsFetchData = (url) => (dispatch) => {
fetch(url)
.then((response) => {return response.json()})
.then((pilots) => {
dispatch(pilotsFetchDataSucces(pilots))
})
.catch((e) => {console.log('Error in pilotsFetchData', e)});
};
这是减速器:
const pilotsReducer = (state = [], action) => {
switch(action.type){
case 'PILOTS_FETCH_DATA_SUCCES':
console.log('pilotsReducer', action.pilots);
return [
...state,
action.pilots
];
default:
return state;
}
}
export default pilotsReducer;
稍后在我的组件中,我想访问这些数据。我正在使用 mapStateToProps。
import React from 'react';
import { connect } from 'react-redux';
import SinglePilot from './SinglePilot.js';
import { pilotsFetchData } from '../actions/pilots';
class Pilots extends React.Component {
componentDidMount () {
this.props.fetchData('https://raw.githubusercontent.com/guidokessels/xwing-data/master/data/pilots.js');
}
render(){
return (
<div>
<h1>Title</h1>
{this.props.query && <p>You searched for: {this.props.query}</p>}
{
//iterate over all objects in this.props.pilots
this.props.pilots.map( (pilot) => {
return (
<SinglePilot
key={pilot.id}
name={pilot.name}
/>
)})
}
</div>
);
}
}
const mapStateToProps = (state) => ({
pilots: state.pilots // is [[Array(278)]] instead of [Array(278)]
});
const mapDispatchToProps = (dispatch) => ({
fetchData: (url) => dispatch(pilotsFetchData(url))
});
export default connect(mapStateToProps, mapDispatchToProps)(Pilots);
我遇到的问题是state.pilots 的值现在是一个长度为 1 的数组,而我想要的数组(长度为 278)在这个数组中。
我知道我可以使用state.pilots[0] 来解决这个问题,但我不喜欢这样。
是什么导致我最初的 Pilots 数组被包裹在另一个数组中?
非常感谢您的帮助!
编辑:添加reducer的代码。
【问题讨论】:
-
你能分享你的reducer代码吗?
-
我在原来的问题中添加了减速器代码。
标签: reactjs redux react-redux fetch redux-thunk