为什么我不能推到状态的阵列? [英] Why can't I push to an array in state?

查看:140
本文介绍了为什么我不能推到状态的阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎没有从API将对象推送到数组状态。这是我的代码

I can't seem to push an object to array in state from an API. This is my code

      async _fetchData(number){
        try{
          await console.log('asd',number)
          let response = await fetch( 'https://www.beanlinked.com/wp-json/wp/v2/media/'+this.state.News[number].featured_media)
          let responseJson = await response.json()
          await console.log("responseJson")
          let tempURL = responseJson.guid
          let url = tempURL.rendered

          for (var i = 0; i < this.state.News.length; i++) {
            const items = this.state.News;
            items[number].URLOnSever = url;

          }

          this.state.News.push({
            URLOnSever : url
          })
          console.log("imageurl",this.state.News.URLOnSever)

          return url
        }catch(e){
          console.log('problem'+e)
        }
      }

我只想将新的URL推送到 this.state 。新闻

I just want to push the new URL to this.state.News.

推荐答案

不要使用 Array#push - 将数组变为状态。使用 setState 而不是使用旧数组添加新数组加上添加的元素设置为状态而不是推送到旧数组:

Don't mutate state, which you are doing with Array#push -- mutating an array inside state. Use setState instead to create a new array with the old array plus added elements set into state instead of pushing to the old one:

this.setState(prevState => ({
  News: [
    ...prevState.News,
    { URLOnServer: url }
 ]
}));

这将将新闻设置为上一个状态新闻数组内容(通过数组扩展语法)加上新对象。它与您的代码相同,但不直接突出状态。了解更多信息,请访问 React文档

This will set News to the previous state's News array contents (via array spread syntax) plus the new object. It's the same as your code, but without mutation of state directly. Learn more at the React documentation.

这篇关于为什么我不能推到状态的阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆