即使我使用this.context.setImageList更新状态以从API获取数据,imageList也为空。我很困惑为什么状态没有更新。我已经花了很多时间在这上面,还没有找到根本原因。如果您能指导我完成它,我将不胜感激。谢谢!
import React, { Component } from 'react';
const ImageListContext = React.createContext({
imageList: [],
error: null,
loading: true,
setError: () => {},
clearError: () => {},
setImageList: () => {},
})
export default ImageListContext
export class ImageListProvider extends Component {
state = {
imageList: [],
error: null,
};
setImageList = imageList => {
this.setState({imageList})
}
setError = error => {
console.error(error)
this.setState({ error })
}
clearError = () => {
this.setState({ error: null })
}
render() {
const value = {
imageList: this.state.imageList,
error: this.state.error,
setError: this.setError,
clearError: this.clearError,
setImageList: this.setImageList,
}
return (
<div>
{this.loading ? <div>Loading Images...</div> :
<ImageListContext.Provider value={value}>
{this.props.children}
</ImageListContext.Provider>}
</div>
)
}
}
import React, { Component } from 'react'
import ImageApiService from '../../services/image-api-service'
import { Section } from '../../components/Utils/Utils'
import ImageListItem from '../../components/ImageListItem/ImageListItem'
import './ImageListPage.css'
import ImageListContext from '../../contexts/ImageListContext'
export default class ImageListPage extends Component {
static contextType = ImageListContext;
componentDidMount() {
//this calls the image API to get all images!
ImageApiService.getImages()
.then(resJson => this.context.setImageList(resJson))
.catch(error => console.log(error))
}
setError = error => {
console.error(error)
this.setState({ error })
}
clearError = () => {
this.setState({ error: null })
}
renderImages() {
const { imageList=[] } = this.context;
console.log(imageList)
return imageList.map(image =>
<ImageListItem
key={image.id}
image={image}
/>
)
}
render() {
return (
<Section list className='ImageListPage'>
{this.context.error
? <p className='red'>There was an error, try again</p>
: this.renderImages()}
</Section>
)
}
}