【问题标题】:Push object from JSON rest api into empty array not working in React将对象从 JSON rest api 推送到空数组中,这在 React 中不起作用
【发布时间】:2020-05-05 11:39:32
【问题描述】:

我正在尝试将来自休息 api 的 JSON 响应中的对象推送到 React 中的空数组中,到目前为止我的代码无法正常工作,我对 React 还很陌生,所以看不出哪里出错了?也许与状态中的功能有关?我收到错误:

Cannot read property 'saved' of undefined

到目前为止的代码:

import React, { Component } from 'react';
import './news-hero.css';
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";

const responsive = {
    superLargeDesktop: {
        breakpoint: { max: 4000, min: 3000 },
        items: 1,
    },
    desktop: {
        breakpoint: { max: 3000, min: 1024 },
        items: 1,
    },
    tablet: {
        breakpoint: { max: 1024, min: 464 },
        items: 1,
    },
    mobile: {
        breakpoint: { max: 464, min: 0 },
        items: 1,
    },
};

class NewsHero extends Component {
    state = {
        loading: false,
        data: [],
        headline: [],
        saved: []
    }

    saved() {
        this.saved.push(this.headline);
        //alert('this is saved kind of');
    }

    onError() {
        this.setState({
            imageUrl: "../assets/img-error.jpg"
        })
    }

    componentDidMount() {
        this.setState({ loading: true })
        fetch('https://newsapi.org/v2/everything?q=timbaland&domains=rollingstone.com,billboard.com&excludeDomains=townsquare.media&apiKey=8')
            .then(headline => headline.json())
            .then(headline => this.setState({ headline: headline.articles, loading: false }, () => console.log(headline.articles)))
    }

    render() {
        return (
            <div className="hero">
                <h2 className="text-left">News</h2>

                {this.state.loading
                    ? "loading..."
                    : <div>
                        <Carousel
                            additionalTransfrom={0}
                            showDots={true}
                            arrows={true}
                            autoPlaySpeed={3000}
                            autoPlay={false}
                            centerMode={false}
                            className="carousel-hero"
                            containerClass="container-with-dots"
                            dotListClass="dots"
                            draggable
                            focusOnSelect={false}
                            infinite
                            itemClass="carousel-top"
                            keyBoardControl
                            minimumTouchDrag={80}
                            renderButtonGroupOutside={false}
                            renderDotsOutside
                            responsive={responsive}>
                            {this.state.headline.map((post, indx) => {
                                return (
                                    <div className="text-left mt-5" key={indx}>
                                        <img className="media-img card-img-top card-img-hero" src={post.urlToImage} alt="Alt text"></img>
                                            <div className="card-body container hero-text-body">
                                                <h1 className="card-title hero-title text-truncate">{post.title}</h1>
                                                <button className="btn-primary btn mt-2 mb-4" onClick={this.saved}>Add this article</button>
                                                <p className="card-text">{post.description}</p>
                                                <a href={post.url} target="_blank" rel="noopener noreferrer">Read More</a>
                                            </div>
                                    </div>
                                )
                            })}
                        </Carousel>

                    </div>
                }
            </div>
        )
    }
}
export default NewsHero;

有什么想法和见解吗?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

无法读取未定义的“已保存”属性

对于saved 或headline,您没有正确引用this.state。

无法读取未定义的属性“状态”

添加一个构造函数并将this 绑定到您的saved 函数。

constructor(props) {
  super(props);
  this.saved = this.saved.bind(this);
}

saved() {
    this.saved.push(this.headline);
    //alert('this is saved kind of');
}

或者将saved定义为箭头函数来绑定this

saved = () => {
    this.saved.push(this.headline);
    //alert('this is saved kind of');
}

应该是

saved() {
  const { headline, saved } = this.state;
  this.setState({ saved: [...saved, headline] });
}

或

saved = () => {
  const { headline, saved } = this.state;
  this.setState({ saved: [...saved, headline] });
}

更新:保存特定的帖子/标题

我现在明白了,如果您希望保存特定标题,那么您需要更新 saved 函数的签名以及如何调用它。

saved = headline => {
  this.setState(
    prevState => ({ saved: [...prevState.saved, headline] })
  );
}

当你作为回调调用它时

<button
  className="btn-primary btn mt-2 mb-4"
  onClick={() => this.saved(post)} // pass the current post defined in the map callback
>
  Add this article
</button>

关于命名的一个小评论,在整个代码中始终以相同的方式引用相同的“对象”在帮助可读性方面大有帮助。 IE。您如何引用标题、帖子和文章。选择一个并保持一致。

this.state.headlines => this.state.headlines.map(headline =&gt; ...

this.state.posts => this.state.posts.map(post =&gt; ...

this.state.articles => this.state.articles.map(article =&gt; ...

【讨论】:

  • 出现错误?解析错误:意外的令牌,应为“,”
  • 缺少一个 }
  • 但即使使用 Drew 代码,也会出现同样的错误 - 无法读取未定义的属性“状态”
  • 我的下一个猜测是saved 函数没有正确绑定到this。更新绑定建议。
  • 感谢它确实以某种方式工作,推送到空数组但是当我控制台记录它时,它在第一次单击 saved() 函数时没有推送任何内容,但是当我再次单击 save() ,它把所有的对象都推到数组中,而不仅仅是我想要的文章,这可能与 render() 方法中的键索引有关吗?
【解决方案2】:
    saved() {
        this.saved.push(this.headline);
        //alert('this is saved kind of');
    }

如果不编写这样的构造函数,就无法定义这样的类方法:

class NewsHero extends Component {
  constructor(props){
    super(props)
    this.saved = this.saved.bind(this)

  }

...the rest of everything you wrote

}

如果不这样做,您的saved 函数就不会绑定到类的实例。它很傻,是的,但这就是类方法在 javasript 中的工作方式。另一种选择是使用箭头函数,如果this 会保留上下文:

    saved = () => {
        this.saved.push(this.headline);
        //alert('this is saved kind of');
    }

我认为这更快更干净,而且很常用。

这是问题1。问题2是您在编写this.saved.push(this.headline)时似乎正在尝试直接修改状态对象。这不是怎么做的。要修改你的状态,你需要使用this.setState函数:

saved = () => {
  this.setState({
    saved: whatever you want this to be
  })
}

但看起来您已经在 fetch 调用中正确设置了状态,所以我不确定您要使用 saved 函数完成什么...?

【讨论】:

  • 所以 saved() 函数应该将特定的文章添加到保存的数组中,这是 rest api 调用中的 JSON 对象。
猜你喜欢
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多