Also, was ich tue, ist die folgende:vom redux Speicher ein Array Erste bringt es in einem anderen Array
Eine Aktion holt eine .json Datei von einer URL und entsendet eine andere Aktion. Der Wert für pilots
ist [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)});
};
Dies ist das Reduktions:
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;
Später in meiner Komponente möchte ich auf diese Daten zugreifen. Ich verwende 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);
Das Problem ich habe, ist, dass der Wert von state.pilots
ist nun ein Array mit der Länge 1 und das Array, das I (mit einer Länge von 278) soll in diesem Array ist.
Ich weiß, dass ich das mit state.pilots[0]
beheben konnte, aber das mag ich nicht. Was bewirkt, dass mein anfängliches Pilots-Array in ein anderes Array eingeschlossen wird?
Vielen Dank für jede Hilfe!
Edit: hinzugefügt den Code für den Reducer.
Könnten Sie Ihr Minderer Code teilen? – mersocarlin
Ich habe den Reducer-Code in meiner ursprünglichen Frage hinzugefügt. – Gwouten