【问题标题】:this.state.articles is undefined in React jsthis.state.articles 在 React js 中未定义
【发布时间】:2022-01-17 01:34:46
【问题描述】:

我正在为我的项目创建一个新闻应用程序,我所做的基本上是从 API 获取新闻文章数组,然后将其存储在我本地内存中的文章数组中,然后我使用 map 方法数组,从而在我的网页上呈现文章,但现在我收到此错误:

image of the error

我看了一些类似的问题,我认为构造函数的范围有什么问题。 编辑:我在 setstate 部分错了,但我只是在尝试,但原始代码是这样的:

this.state = {
  articles: this.articles
}

上面的代码是在下面的代码是完整代码之前的setstate位置的原始代码

 articles = [];
constructor() {
    super();
    console.log(typeof articles);
      this.state = {
        articles: this.articles
    }
    // let category = 'top-headlines';
    // let country = 'in';

}

async componentDidMount() {
    const YOUR_API_KEY = 'cant show you this';
    // let q = '';
    let url = `https://newsapi.org/v2/top-headlines?country=in&apiKey=${YOUR_API_KEY}`;
    const FetchNews = async () => {
        const response = await fetch(url);
        const parsedjson = await response.json();
        console.log(parsedjson);
        this.setState({ articles: parsedjson.articles });
    }
    FetchNews();
}

render() {
    return (
        <div className="container p-1" style={{ backgroundColor: '#F0CE57' }}>

            <div className="noogle">
                <h1>Noogle</h1>
                <input type="text" placeholder='Search News' />
            </div>
            <div className="row">
                {this.state.articles.map((element) => {
                    return <div className="col-md-4" key={element.url}>
                        <NewsCard title={element.title} desc={element.description} imgurl={element.urlToImage} url={element.url} />
                    </div>
                })}
            </div>
        </div>

    )
}

}

【问题讨论】:

  • 您没有正确初始化状态。在构造函数中你只是将属性设置为一个对象,不要在这里调用setState
  • @BrianThompson 实际上我只是在尝试,但实际代码是这样的:`this.state = {articles:this.articles}`

标签: reactjs api react-class-based-component


【解决方案1】:

为什么要在构造函数中设置状态。相反,当您调用 this.setState() 函数时,它将设置文章的状态 试试这段代码

 articles = [];
constructor() {
    super();
    console.log(typeof articles);
    this.state = {
        articles : []
    }
    // let category = 'top-headlines';
    // let country = 'in';

}

【讨论】:

    【解决方案2】:

    因为this.state 没有名为articles 的属性。它有一个名为this 的属性,该属性设置为...无论this.setState 在尝试将状态设置为this.articles 时返回的内容,该属性也不存在。这根本不是你想要的:

    this.state = {
        this: this.setState({ articles: this.articles })
    }
    

    我不知道你是从哪里拼凑出这个例子的,但这全错了。只需将状态值初始化为一个空数组即可:

    this.state = {
        articles: []
    }
    

    然后在初始渲染时,您根本没有要显示的记录。当 AJAX 操作完成并设置新的状态值时,您将在下一次重新渲染时获得记录。

    您不需要(或不想要)您的全局 articles 变量。它会诱使您直接改变值并导致奇怪的错误。

    【讨论】:

      猜你喜欢
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      • 2021-07-03
      • 2018-11-13
      • 2018-09-28
      相关资源
      最近更新 更多