React-Router笔记(第五天)

156 阅读1分钟

一. Returning Responses in loader()

const res = new Response('any data',{status: 201});
return res;

二. Error Handling with Custom Errors

if (!response.ok) {
    throw new Response(JSON.stringify({message: 'Could not fetch events.'}),status: 500)
    }
{
    path: '/',
    element: <RootLayout />,
    errorElement: <ErrorPage/>,
}
import { useRouteError} from 'react-router-dom';
function ErrorPage() {
    const error = useRouteError();
    let message = 'Some thing went wrong!';
    if(error.status === 500) {
        message = JSON.parse(error.data).message;
    }
    if(error.status === 404) {
        message = 'Could not find resource or page.'
    }
    return(
        <p>{message}<p>
    )
}
export default ErrorPage;

三. 如何改善当服务器没有返回时要抛出的错误(使用json()utility function)

1.引入包

import {json} from 'react-router-dom'

2.调用函数

if(!response.ok) {
    return json({message: 'Could not fetch events'}, 
    {
        status: 500,
    });
}

四. useRouteLoaderData()

这个函数可以接收一个id

五. Working with action() functions

{
    path: 'new',
    element:<NewEventPage />,
    action: () => {}, //action接收一个函数,当然不写在这里
}

在这个action函数里我们可以向后端发送请求

import {redirect} from 'react-router-dom';
export async function action({request,params}) {
    const data = await request.formData();
    const eventData = {
        title: data.get('title'),
        image: data.get('image'),
        date: data.get('date'),
        description: data.get('description'),
    }
    fetch('http://localhost:8080/events',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(eventData)
    });
    
    if (!response.ok) {
        throw json({message:'Could not save event.'}, {status: 500 })
    }
    return redirect('/events');
}