Я обращаюсь к своему API, чтобы получить конкретный объект, передающий идентификатор, который работает нормально, когда я попадаю в console.log в методе mapStateToProps, он записывает мне весь объект, но в моем состоянии где есть "this.props.anuncio", "anuncio" не определено, что я делаю не так? ниже показано, как я использую редуктор и действие.
import React from 'react'
import PropTypes from 'prop-types'
import { fetchAnuncio } from '../../actions/anuncios';
import { connect } from 'react-redux';
import Avatar from 'react-avatar';
import star from '../../imgs/star.png';
class AnuncioDetalhes extends React.Component {
constructor(props) {
super(props);
this.state = {
id: this.props.anuncio ? this.props.anuncio.id : null,
img: this.props.anuncio ? this.props.anuncio.img : null
}
}
componentDidMount() {
if (this.props.match.params.id) {
this.props.fetchAnuncio(this.props.match.params.id);
}
}
render () {
const {id, img} = this.state;
return (
<div>
</div>
);
}
}
AnuncioDetalhes.propTypes = {
fetchAnuncio: PropTypes.func.isRequired,
history: PropTypes.object.isRequired
}
function mapStateToProps(state, props) {
if(props.match.params.id) {
console.log(state.anuncios.find(item => item.id === 4))
return {
anuncio: state.anuncios.find(item => item.id === props.match.params.id)
}
}
return { anuncio: null };
}
export default connect(mapStateToProps, {fetchAnuncio})(AnuncioDetalhes);
Редуктор:
import { SET_ANUNCIOS, ANUNCIO_FETCHED } from '../actions/types';
export default function anuncios(state = [], action = {}) {
switch(action.type) {
case ANUNCIO_FETCHED:
const index = state.findIndex(item => item.id === action.anuncio.id);
if(index > -1) {
return state.map(item => {
if (item.id === action.anuncio.id) return action.anuncio;
return item;
});
} else {
return [
...state,
action.anuncio
];
}
case SET_ANUNCIOS:
return action.anuncios;
default: return state;
}
}
Действие:
import axios from 'axios';
import Constants from '../components/Constants'
import { SET_ANUNCIOS, ANUNCIO_FETCHED } from './types';
export function setAnuncios(anuncios) {
return {
type: SET_ANUNCIOS,
anuncios
}
}
export function anuncioFetched(anuncio) {
return {
type: ANUNCIO_FETCHED,
anuncio
};
}
export function fetchAnuncios(cidade) {
return dispatch => {
return axios.get(Constants.BASE_URL + "anuncios/?user__cidade=" + cidade + "&status=2").then(res => {
dispatch(setAnuncios(res.data.results));
});
}
}
export function fetchAnuncio(id) {
return dispatch => {
return axios.get(Constants.BASE_URL + "anuncios/" +`${id}`).then(res => {
dispatch(anuncioFetched(res.data));
});
}
}