gpt4 book ai didi

javascript - mapStateToProps 对象未定义

转载 作者:行者123 更新时间:2023-11-30 11:19:48 27 4
gpt4 key购买 nike

我正在调用我的 API 以使用其 ID 获取特定对象。

当我在 mapStateToProps 方法中调用 console.log 时,打印了整个对象,但状态的“anuncio”属性未定义当我尝试使用 this.props.anuncio 访问它时。我做错了什么?

下面是我如何使用 reducer 和 action。

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);

reducer :

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;
}
}

Action :

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));
});
}
}

最佳答案

我认为您应该使用 componentWillReceiveProps 生命周期方法来获取更新的 Prop 。

componentWillReceiveProps = (nextProps)  => {
console.log(nextProps)
}

关于javascript - mapStateToProps 对象未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50235666/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com