【问题标题】:Uncaught Error: Objects are not valid as a React child when trying to render html in react未捕获的错误:尝试在反应中呈现 html 时,对象作为 React 子项无效
【发布时间】:2018-08-08 17:32:58
【问题描述】:

这是我的应用程序的简单版本

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

它显然看起来像是一个数组,并且通过放置 .toArray 会导致它未定义。

如何解决我的这个问题。

非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: reactjs local-storage


    【解决方案1】:

    您可以只将图像数据数组存储在 state 中,然后在 render 方法中派生 JSX,而不是将 JSX 存储在 state 中(只是 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>
      );
    }
    

    【讨论】:

      【解决方案2】:

      错误背后的原因是您在渲染返回中包含了 Object {this.state.images}。如果不是那样写{this.state.images.length},它将正确呈现。您需要引用作为字符串值的对象的属性,或者将对象转换为所需的字符串表示形式。如果您真的想查看对象的内容,一个选项可能是JSON.stringify。此外,您可能会认为图像是数组,这是真的,但在 JS 世界中,它被视为一个对象。如果对于任何数组,你会做 typeof yourArr,它会说 Object

      【讨论】:

        猜你喜欢
        • 2017-08-04
        • 2017-04-18
        • 1970-01-01
        • 1970-01-01
        • 2018-04-20
        • 2018-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多