>本教程演示了使用帖子添加和顯示功能構建博客的用戶主頁。 以前的部分涵蓋了註冊和登錄。 該部分專注於通過路由,後保存和郵政檢索之間的數據傳輸。
>提供了示例著陸頁UX:
入門:
>克隆存儲庫,並使用以下方式安裝依賴項
npm install npm start
>服務器端增強:
添加新帖子:
app.get('/api/get/post', (req, res, next) => { const post_id = req.query.post_id; pool.query(`SELECT * FROM posts WHERE pid=`, [post_id], (q_err, q_res) => { res.json(q_res.rows); }); });
app.post('/api/post/posttodb', (req, res, next) => { const values = [req.body.title, req.body.body, req.body.uid, req.body.username]; pool.query(`INSERT INTO posts(title, body, user_id, author, date_created) VALUES(, , , , NOW())`, values, (q_err, q_res) => { if (q_err) return next(q_err); res.json(q_res.rows); }); });客戶端開發:
>客戶端應用程序現在包括一個著陸頁和郵政顯示頁面。 路由已更新:
著陸頁(const router = createBrowserRouter([ { path: "/", element: <app></app> }, // ... { path: "/landing", element: <landing></landing> }, { path: "/post", element: <post></post> } ]);):
成功登錄/註冊後,用戶將重定向到著陸頁,通過路由的landing/index.js
接收電子郵件,UID和用戶名
>狀態變量跟踪帖子(state
)和刷新標誌(
import { useLocation } from 'react-router-dom'; // ... const { state } = useLocation(); const { email, username, uid } = state;加載用戶帖子:
posts
refresh
ui通過useEffect
迭代,顯示標題;單擊標題導航到
useEffect(() => { loadAllPostsOfUser(); }, []); const loadAllPostsOfUser = () => { axios.get('/api/get/allposts') .then(res => setPosts(res.data)) .catch((err) => console.log(err)); };)管理可見性:
posts
/post
模態樣式在Modal.js
中。 登錄頁麵包括一個打開模式的按鈕,一個用於提交新帖子的表格和帖子列表。
const Modal = ({ handleClose, show, children }) => { // ... };>。
>
modal.css
handleSubmit
>/api/post/posttodb
>發布顯示頁面(
const handleSubmit = (event) => { event.preventDefault(); const data = { title: event.target.title.value, body: event.target.body.value, username: username, uid: uid }; axios.post('/api/post/posttodb', data) .then(response => console.log(response)) .catch((err) => console.log(err)) .then(setTimeout(() => setRefresh(!refresh), 700)); };
>
>此頁面顯示單個帖子。 它使用post.js
獲得>,
。 useLocation
>通過post_id
。
email
username
useEffect
結論:/api/get/post
import { useLocation } from 'react-router-dom'; // ... const { state } = useLocation(); const { email, username, uid, post_id } = state || { username: 'Tuts+ Envato', email: 'tuts@envato.com', uid: '123', post_id: 1 }; const [post, setPost] = useState(); // ... useEffect(() => { if (post_id && uid) { axios.get('/api/get/post', { params: { post_id: post_id } }) .then(res => res.data.length !== 0 ? setPost({ likes: res.data[0].likes, like_user_ids: res.data[0].like_user_id, post_title: res.data[0].title, post_body: res.data[0].body, post_author: res.data[0].author }) : null) .catch((err) => console.log(err)); } }, [post_id]);>
以上是使用React創建博客應用程序,第3部分:添加和顯示帖子的詳細內容。更多資訊請關注PHP中文網其他相關文章!