>本教程演示了使用帖子添加和显示功能构建博客的用户主页。 以前的部分涵盖了注册和登录。 该部分专注于通过路由,后保存和邮政检索之间的数据传输。
>提供了示例着陆页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中文网其他相关文章!