用 React + Redux 构建了个同构的博客,心力交瘁(Nodejs相关)

用 React + Redux 构建了个同构的博客,心力交瘁(Nodejs相关)
主要做了三件事:

1. 试用了 Redux
2. 实现了服务端渲染
3. 完善了自己造的一个 node.js 服务端框架轮子([eliter]( https://github.com/nameoverflow/eliter))

只做了点微小的贡献,很惭愧。

实现同构的过程中踩了一些坑,打算总结几篇文章,[第一篇关于数据同步的在这]( https://hcyue.me/article/56de8c7e47df78380df061a1),文笔不行大家轻拍__(:з」∠)__


2 回复

被 reducers 恶心到吐,感觉为了解决 A 问题,引入 B , C 问题,然后为了结局 BC 引入了 DEF 。。


在构建同构(也称为“同端”)博客应用时,使用 React 和 Redux 结合 Node.js 相关技术确实是一个挑战,但也非常具有成就感。以下是一些关键点和代码示例,希望对你有所帮助。

1. 项目结构

确保你的项目结构清晰,可以大致分为 clientservershared 三个目录:

/my-isomorphic-blog
  /client
    /components
    /redux
    ...
  /server
    /routes
    /controllers
    ...
  /shared
    /models
    /utils
    ...
  ...

2. React + Redux

在客户端,使用 React 组件和 Redux 管理状态。例如,一个简单的 Redux action 和 reducer:

// actions/index.js
export const FETCH_POSTS = 'FETCH_POSTS';
export const fetchPosts = () => ({
  type: FETCH_POSTS,
  payload: axios.get('/api/posts')
});

// reducers/postsReducer.js
const initialState = { posts: [] };
export default (state = initialState, action) => {
  switch (action.type) {
    case FETCH_POSTS:
      return { ...state, posts: action.payload.data };
    default:
      return state;
  }
};

3. Node.js 服务器

在服务器端,使用 Express.js 处理路由和 API 请求。例如:

// server/routes/api.js
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');

router.get('/posts', async (req, res) => {
  const posts = await Post.find();
  res.json(posts);
});

module.exports = router;

希望这些代码示例和建议能帮助你更好地管理和优化你的同构博客应用。加油!

回到顶部