未捕获的错误:尝试在react中呈现html时,对象作为React子元素无效

时间:2018-08-08 17:32:59

标签: reactjs local-storage

这是我的应用的简单版本

constructor(props) {
    super(props);

    let images = JSON.parse(localStorage.getItem('images'))
    images = images? images : []
    this.match = props.match
    // the images part of this state should be handled by the app component but for now i'll use localStorage
    console.log('constructor', images);

    this.state = {
      count: 0,
      increment: 9,
      images: images
    }

    if (this.state.images.length === 0) {
      this.getImages(this.state);
    }
  }

  build_gallery_items = (images) => {
    return images.map((src, id) => {

      return (
        <div className="item col s4" key={src}>
          <a data-fancybox="gallery" href={src} data-caption={`<a href='${src}' download>Download</a>`}>
            <img className="image-item" src={src} alt="Stuff about this" />
          </a>
        </div>
      );
    });
  }

getImages = (state) => {
   let url = './server/getImages.php'

    axios.post(url, state)
      .then(res => {

        this.setState({
          images: this.state.images.concat(this.build_gallery_items(res.data.images))
        }, () => {
          localStorage.setItem('images', JSON.stringify(this.state.images))
        })
      })
      .catch(err => {
        console.log(err);
      })
  }

render() {

    // console.log('images', this.state.images);
    return (


              <div className='wrap'>
                <h2>Image Gallery</h2>
                <div className="container">
                  <div className='row'>
                    {this.state.images}
                  </div>
                </div>
              </div>

    )
  }

ajax调用工作正常,将其存储在本地存储中并显示图像。然后,当我刷新页面以使用localstorage中当前使用的内容时,出现“对象无效错误”。这是我尝试使用它之前在控制台中打印的内容。

enter image description here

它显然看起来像是一个数组,并且通过放置.toArray导致它变得不确定。

我该如何解决这个问题。

任何帮助都非常有用。谢谢。

2 个答案:

答案 0 :(得分:1)

您可以只以状态存储图像数据数组,然后以render方法派生JSX,而不是将JSX存储为状态(React.createElement calls under the hood)。

这样images数组将被正确地字符串化和解析。

getImages = state => {
  let url = "./server/getImages.php";

  axios
    .post(url, state)
    .then(res => {
      this.setState(
        {
          images: res.data.images
        },
        () => {
          localStorage.setItem("images", JSON.stringify(this.state.images));
        }
      );
    })
    .catch(err => {
      console.log(err);
    });
};

render() {
  return (
    <div className="wrap">
      <h2>Image Gallery</h2>
      <div className="container">
        <div className="row">
          {this.state.images.map((src, id) => (
            <div className="item col s4" key={src}>
              <a
                data-fancybox="gallery"
                href={src}
                data-caption={`<a href='${src}' download>Download</a>`}
              >
                <img
                  className="image-item"
                  src={src}
                  alt="Stuff about this"
                />
              </a>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

答案 1 :(得分:0)

错误的原因是您在渲染返回中包含对象{this.state.images}。如果不是,您将编写{this.state.images.length},它将正确呈现。您将需要引用对象的属性(它是字符串值),或者将Object转换为所需的字符串表示形式。如果您确实想查看对象的内容,则一个选项可能是JSON.stringify。另外,您可能会认为图像是数组,这是正确的,但在JS世界中,它被视为对象。如果要对任何数组执行typeofArr,它将显示Object