我从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
}
}
内容呈现,但在此之前有一瞬间,它似乎试图在成功检索数据之前呈现内容,这会在控制台中显示以下错误:
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响应。
任何帮助表示感谢。
答案 0 :(得分:1)
您是否在redux商店中定义了初始状态?
您可以尝试这种方式:
return singlePhoto ?
(<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>) : null