Answer the question
In order to leave comments, you need to log in
How to correctly pass a parameter from componentDidMount to mapDispatchToProps?
Hello, I ran into a problem that you need to pass this.props.match.params.id to the fetchOnePhone argument, which is in mapDispatchToProps, but it is only initialized in componentDidMount
import React, { Component } from 'react'
import Image from './image'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
import {fetchOnePhone} from '../actions/phone'
import ErrorElem from './error.js'
import Loader from './loader.js'
import withPhonestoreService from './hoc.js'
import compose from '../utils/compose.js'
import './style/details.css'
const DetailRender = ({phone}) => {
const {title, img, price, company, info} = phone
return (
<div className="container detail">
<div className="l__col">
<h1>{title}</h1>
<Image {...img}/>
</div>
<div className="r__col">
<p className="detail__company">
Компания: {company}
</p>
<div>
<p className="detail__info">
Информация:<br/>{info}
</p>
</div>
<p className="detail__price">
Цена: {price} rub
</p>
<Link to={`/cart`}>
<div className="elem__link buy">Купить</div>
</Link>
</div>
</div>
)
}
class Details extends Component {
componentDidMount() {
const elemId = parseInt(this.props.match.params.id, 10)
this.props.fetchOnePhone(elemId)
}
render() {
const {phoneStore ,error, loading} = this.props
if(loading) {return <Loader />}
if(error) {return <ErrorElem />}
return <DetailRender phone={phoneStore[0]} />
}
}
const mapStateToProps = ({ phone: { phoneStore, loading, error }}) => {
return { phoneStore, loading, error };
};
const mapDispatchToProps = (dispatch, { phonestoreService }) => {
return {
fetchOnePhone: fetchOnePhone(phonestoreService, dispatch, elemId )
}
};
export default compose(
withPhonestoreService(),
connect(mapStateToProps, mapDispatchToProps)
)(Details)
Answer the question
In order to leave comments, you need to log in
const mapDispatchToProps = {
fetchOnePhone,
};
componentDidMount() {
const { phonestoreService, match, fetchOnePhone } = this.props;
const { id } = match.params;
fetchOnePhone(phonestoreService, id);
}
fetchOnePhone(id);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question