为什么我的上下文未按预期更新状态?

时间:2019-11-28 15:44:10

标签: reactjs react-context

即使我使用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>
    )
  }
}
  • 使用Context使用API​​中的数据更新imageList数组,并从数组中获取数据以进行显示
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>
     )
  }
}

0 个答案:

没有答案