0
我從一個遠程API獲取數據中componentDidMount
:控制檯錯誤,同時等待API響應 - 反應,和/終極版
componentDidMount() {
this.props.fetchRemoteData('photos')
}
然後將接收到的數據傳遞給我的組件道具mapStateToProps
,使用選擇器從接收到的陣列篩選特定對象:
const mapStateToProps = (state, { params }) => {
const photoId = parseInt(params.photoId)
return {
singlePhoto: getSinglePhoto(state.filteredList.photos.jsonArray, photoId),
isFetching: state.filteredList.photos.isFetching
}
}
內容呈現,但是有一個分裂之前第二是,這裏它似乎是試圖將呈現內容的數據被成功地檢索之前,這帶來了以下e RROR在控制檯:
Uncaught TypeError: Cannot read property 'charAt' of undefined
undefined
在這裏指的是this.props.singlePhoto
。但是,當singlePhoto收到內容呈現的數據有效載荷時。
這裏是我的容器組件:
class PhotoSingle extends Component {
componentDidMount() {
this.props.fetchRemoteData('photos')
}
render() {
const {singlePhoto, isFetching} = this.props
const photoTitle = capitalizeFirstLetter(singlePhoto.title)
return (
<div>
<PhotoSingleImg singlePhoto={singlePhoto} photoTitle={photoTitle} isFetching={isFetching}/>
</div>
)
}
}
const mapStateToProps = (state, { params }) => {
const photoId = parseInt(params.photoId)
return {
singlePhoto: getSinglePhoto(state.filteredList.photos.jsonArray, photoId),
isFetching: state.filteredList.photos.isFetching
}
}
import * as actions from '../actions/actionCreators'
PhotoSingle = connect(mapStateToProps, actions)(PhotoSingle)
export default PhotoSingle;
而且我表象組件:
const PhotoSingleImg = ({ singlePhoto, photoTitle, isFetching }) => {
if (isFetching) {
return <h4>Fetching data...</h4>
}
return (
<div>
<h1>Single Photo</h1>
<h3>Title</h3>
<hr />
<img className='single-photo' src={singlePhoto.url} />
<p>Album ID: {singlePhoto.albumId} | Photo ID: {singlePhoto.id}</p>
</div>
)
}
export default PhotoSingleImg;
我不確定如何使它這樣的內容將只嘗試渲染之後我收到了API響應。
任何幫助表示讚賞。
完美!這是固定的 - 謝謝! – Paulos3000