React-Router笔记(第四天)

77 阅读1分钟

一. Data Fetching with a loader()

与path,element 等props并列的还有一个loader props 这个props可以用来获取数据。

{
    index: true,
    element: <EventPage/>,
    loader: async () => {
        const response = await fetch('http://localhost:8080/events');
        if(!response.ok) {
        
        } else {
            const resData = await response.json();
            return resData.events;
        }
    },
}

当我们return data的时候,我们可以在任何更低层次或者同样层次的page上获取到这个data。

二. 如何在任意的更低层次或者同样层次的页面上获取到数据

  1. 引入包
import { useLoaderData } from 'react-router-dom'
  1. 调用函数
const events = useLoaderData();

events就是我们想要拿到的数据

三. 我们应该把loader()函数的代码存在相应的页面中,而不是直接存在app.js中

export async function loader() {
     const response = await fetch('http://localhost:8080/events');
        if(!response.ok) {
        
        } else {
            const resData = await response.json();
            return resData.events;
        }
}

四. Reflecting the current navigation state In the UI

  1. 引入包
import { useNavigation } from 'react-router-dom'
  1. 调用函数
const navigation = useNavigation();
  1. 使用navigation的property state
{navigation.state === 'loading' && <p>Loading...</p>}