4月16日 web学习笔记

一、服务端渲染(SSR)与静态生成(SSG)
服务端渲染(SSR)
定义:在服务器上生成 HTML 页面,然后发送给客户端。
优势:提升首屏加载速度,改善 SEO。
工具:Next.js(React)、Nuxt.js(Vue)、SvelteKit(Svelte)。
静态生成(SSG)
定义:在构建时生成静态 HTML 文件。
优势:极快的加载速度,适合内容不频繁更新的网站。
工具:Next.js、Gatsby(React)、Nuxt.js。
Next.js 示例
安装:

npx create-next-app@latest my-app
cd my-app
npm run dev
页面路由:
文件夹结构:pages 文件夹中的文件自动映射为路由。
SSR 示例:
jsx

// pages/index.js
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}

function Home({ data }) {
return

{data.title}
;
}

export default Home;
SSG 示例:
jsx

// pages/about.js
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}

function About({ data }) {
return

{data.title}
;
}

export default About;
二、GraphQL 与 Apollo Client
GraphQL 简介
定义:一种用于 API 的查询语言。
优势:客户端可以精确请求所需数据,减少过量数据传输。
GraphQL 服务器
工具:Apollo Server、Express。
示例:
JavaScript

const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
type Post {
id: ID!
title: String!
content: String!
}

type Query {
    getPosts: [Post]
}

`;

const posts = [
{ id: '1', title: 'Hello World', content: 'This is my first post' },
];

const resolvers = {
Query: {
getPosts: () => posts,
},
};

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => console.log(Server ready at ${url}));
Apollo Client
安装:
bash

npm install @apollo/client graphql
示例:
jsx

import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
uri: 'http://localhost:4000',
cache: new InMemoryCache(),
});

const GET_POSTS = gql query GetPosts { getPosts { id title content } };

function App() {
const { loading, error, data } = useQuery(GET_POSTS);

if (loading) return <p>加载中...</p>;
if (error) return <p>出错: {error.message}</p>;

return (
    <div>
        {data.getPosts.map(post => (
            <div key={post.id}>
                <h2>{post.title}</h2>
                <p>{post.content}</p>
            </div>
        ))}
    </div>
);

}
三、状态管理(Redux Toolkit)
Redux Toolkit 简介
定义:Redux 的官方状态管理库,简化 Redux 开发流程。
优势:减少样板代码,提升开发效率。
安装:

npm install @reduxjs/toolkit react-redux
示例
创建 Slice:
JavaScript

// features/counter/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: (state) => state + 1,
decrement: (state) => state - 1,
},
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
配置 Store:

// app/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export default configureStore({
reducer: {
counter: counterReducer,
},
});
使用 Redux Provider:
jsx

import { Provider } from 'react-redux';
import store from './app/store';

function App() {
return (



);
}
使用 Redux Hooks:
jsx

import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './features/counter/counterSlice';

function Counter() {
const count = useSelector(state => state.counter);
const dispatch = useDispatch();

return (
    <div>
        <p>计数: {count}</p>
        <button onClick={() => dispatch(increment())}>+1</button>
        <button onClick={() => dispatch(decrement())}>-1</button>
    </div>
);

}
四、实战练习
Next.js 项目
创建一个 Next.js 项目,实现 SSR 和 SSG 页面。
使用 getServerSideProps 和 getStaticProps 获取数据。
GraphQL API
使用 Apollo Server 创建一个简单的 GraphQL API。
使用 Apollo Client 在 React 中查询数据。
Redux Toolkit 应用
使用 Redux Toolkit 管理复杂状态。
实现一个计数器应用,支持加减操作。

posted @ 2025-04-16 23:03  头发少的文不识  阅读(34)  评论(0)    收藏  举报