Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何仅在对象内的所有ID完成提取后设置状态_Javascript_Reactjs - Fatal编程技术网

Javascript 如何仅在对象内的所有ID完成提取后设置状态

Javascript 如何仅在对象内的所有ID完成提取后设置状态,javascript,reactjs,Javascript,Reactjs,我试图在完成一个获取操作循环后设置状态(在数据获取完成之前显示一个加载程序)。我正在使用async函数按data.map执行此操作,但它仍在运行,并且我的setState在此之前发生。如果你知道怎么解决这个问题,我是不是遗漏了什么 这是我的密码: class App extends Component { constructor() { super(); this.state = { posts: [], l

我试图在完成一个获取操作循环后设置状态(在数据获取完成之前显示一个加载程序)。我正在使用
async
函数按data.map执行此操作,但它仍在运行,并且我的
setState
在此之前发生。如果你知道怎么解决这个问题,我是不是遗漏了什么

这是我的密码:

class App extends Component {
      constructor() {
        super();
        this.state = { 

          posts: [],
          loading: true
        }
      }

      async componentDidMount() {
        await this.fetchNews();    
        this.setState({loading: false})

      }

      async fetchNews() {        
        await fetch('https://hacker-news.firebaseio.com/v0/newstories.json')
          .then(response => response.json())
          .then((data) => {
            data.slice(0,10).map((newsId) => {
               fetch('https://hacker-news.firebaseio.com/v0/item/' + newsId + '.json')
                .then(response => response.json())
                .then((itemDetail) => {
                  this.setState({ posts: [...this.state.posts, itemDetail] })
                  console.log('Fetching in progress');                  
                })
                return true;
            })
            console.log('done finished');
          })           
        }    
      render() {    
        var post = this.state.posts;
        const loading = this.state.loading;
        console.log(post)
        const listItems = post.map((link) =>
        <li key={link.id}>{link.title}</li> );

      return <div>
                  {loading ? <Loader type="MutatingDots" color="#somecolor" height={80} width={80} /> : <div>{listItems}</div>}        
        </div>;
     }    
}

export default App;
类应用程序扩展组件{
构造函数(){
超级();
this.state={
员额:[],
加载:正确
}
}
异步组件didmount(){
等待此消息。fetchNews();
this.setState({loading:false})
}
异步获取新闻(){
待命https://hacker-news.firebaseio.com/v0/newstories.json')
.then(response=>response.json())
。然后((数据)=>{
data.slice(0,10).map((newId)=>{
取('https://hacker-news.firebaseio.com/v0/item/“+newsId+”.json')
.then(response=>response.json())
。然后((itemDetail)=>{
this.setState({posts:[…this.state.posts,itemDetail]})
log('Fetching in progress');
})
返回true;
})
console.log('done finished');
})           
}    
render(){
var post=this.state.posts;
常量加载=this.state.loading;
控制台日志(post)
const listItems=post.map((链接)=>
  • {link.title}
  • ); 返回 {正在加载?:{listItems} ; } } 导出默认应用程序;
    这是我的控制台日志,当fetch仍在运行时,您可以看到在开始时打印的done finished消息。

    您可以在调用console.log的fetchnews函数中设置状态值

    class App extends Component {
      constructor() {
        super();
        this.state = { 
    
          posts: [],
          loading: true
        }
      }
    
      async componentDidMount() {
        await this.fetchNews();
      }
    
      async fetchNews() {
    
        await fetch('https://hacker-news.firebaseio.com/v0/newstories.json')
          .then(response => response.json())
          .then((data) => {
            data.slice(0,10).map((newsId) => {
               fetch('https://hacker-news.firebaseio.com/v0/item/' + newsId + '.json')
                .then(response => response.json())
                .then((itemDetail) => {
                  this.setState({ posts: [...this.state.posts, itemDetail] })
                  console.log('Fetching in progress');
    
    
                })
                return true;
            })
            console.log('done finished');
            this.setState({loading: false})
          }) 
    
        }
    
    
    
      render() {
    
        var post = this.state.posts;
        const loading = this.state.loading;
        console.log(post)
        const listItems = post.map((link) =>
        <li key={link.id}>{link.title}</li> );
    
      return <div>
                  {loading ? <Loader type="MutatingDots" color="#somecolor" height={80} width={80} /> : <div>{listItems}</div>}
    
    
    
        </div>;
      }
    
    }
    
    export default App;
    
    类应用程序扩展组件{
    构造函数(){
    超级();
    this.state={
    员额:[],
    加载:正确
    }
    }
    异步组件didmount(){
    等待此消息。fetchNews();
    }
    异步fetchNews(){
    待命https://hacker-news.firebaseio.com/v0/newstories.json')
    .then(response=>response.json())
    。然后((数据)=>{
    data.slice(0,10).map((newId)=>{
    取('https://hacker-news.firebaseio.com/v0/item/“+newsId+”.json')
    .then(response=>response.json())
    。然后((itemDetail)=>{
    this.setState({posts:[…this.state.posts,itemDetail]})
    log('Fetching in progress');
    })
    返回true;
    })
    console.log('done finished');
    this.setState({loading:false})
    }) 
    }
    render(){
    var post=this.state.posts;
    常量加载=this.state.loading;
    控制台日志(post)
    const listItems=post.map((链接)=>
    
  • {link.title}
  • ); 返回 {正在加载?:{listItems} ; } } 导出默认应用程序;
    在map中执行异步操作使用Promise。所有这些都可以正常工作

    const fetchNews = async () =>
      await fetch('https://hacker-news.firebaseio.com/v0/newstories.json')
        .then((response: any) => response.json())
        .then(async (data: any) => {
          let news = data.slice(0, 10);
          await Promise.all(
            news.map(async (newsId: any) => {
              await fetch('https://hacker-news.firebaseio.com/v0/item/' + newsId + '.json')
                .then((response: any) => response.json())
                .then((itemDetail: any) => {
                   this.setState({ posts: [...this.state.posts, itemDetail] });
                  console.log('Fetching in progress', newsId);
                });
              return true;
            })
          );
          console.log('done finished');
        });
    

    不,我在开始打印已完成的控制台日志之前尝试了此操作,之后仍在提取阵列。添加的控制台日志请参阅imageHappy帮助:)