0

我一直在关注 Ben Awad 的视频,并试图扩展这个想法以响应SuspenseList,但当我更改revealOrder. 在所有情况下,端点都被一个接一个地调用,并以forwards模式加载。

演示回购

const fetchPerson = () => {
    return fetch('https://randomuser.me/api').then(x => x.json()).then(x => x.results[0]); 
}; 

const wrapPromise = (promise) => {
    let status = 'pending'; 
    let result = '';
    let suspender = promise.then(r => {
        status = 'success'; 
        result = r;
    }, e => { 
        status = 'error'; 
        result = e; 
    }) 

    return {
        read(){
            if (status === 'pending'){
                throw suspender; 
            } else if (status === 'error'){
                throw result; 
            }
            return result; 
        }
    }
} 

export const createResource = () => {
    return {
        person1: wrapPromise(fetchPerson()),
        person2: wrapPromise(fetchPerson()),
        person3: wrapPromise(fetchPerson()),
        person4: wrapPromise(fetchPerson()),
        person5: wrapPromise(fetchPerson()),
        person6: wrapPromise(fetchPerson())
    }
}




import React, { Suspense } from 'react';
import './App.css';
import { createResource } from './PersonApi';
import { Person } from './Person'; 

const resource = createResource(); 

function App() {
  return (
      <div className="App">
        <Suspense fallback={<h1>loading...</h1>} revealOrder="together">
          <Suspense fallback={<h1>loading person 1</h1>}>
            <Person resource={resource} num="person1" />
          </Suspense>
          <Suspense fallback={<h1>loading person 2</h1>}>
            <Person resource={resource} num="person2" />
          </Suspense>
          <Suspense fallback={<h1>loading person 3</h1>}>
            <Person resource={resource} num="person3"/>
          </Suspense>
          <Suspense fallback={<h1>loading person 4</h1>}>
            <Person resource={resource} num="person4"/>
          </Suspense>
          <Suspense fallback={<h1>loading person 5</h1>}>
            <Person resource={resource} num="person5"/>
          </Suspense>
          <Suspense fallback={<h1>loading person 6</h1>}>
            <Person resource={resource} num="person6"/>
          </Suspense>
        </Suspense>
      </div>
  );
}

export default App;


import React from 'react'; 


export const Person = ({ resource, num  }) => {
    const person = resource[num].read(); 
    return (<div>Loaded {num}: - {person.name.first}</div>)
}; 

4

0 回答 0