Come and join us!
“The Newbies of Little Wo Shan” provides front-end developers with technical information and a series of basic articles. For a better user experience, please go to xhs-rookies.com/ to learn the latest articles.
“Code Tailor “, if you are interested in our article, or would like to make some suggestions, please follow the official account of “Rookie of Xiaohe Mountain” on wechat and contact us. You can also view our article on wechat. Every suggestion or approval is a great encouragement to us!
Actual case: Message function
We’ve learned some of the basics of react-hooks, and now we’re in the field.
The functionality of the project is similar to that of our React tutorial. For details, see the React series – Practical case: Add login
The effect
We want to do the actual combat is very simple, is a simple message function.
Effect:
The Login page
Login Status Maintenance
If we log in successfully, we should have a place for storing information to prepare for authentication later. We use localStorage to do data persistence processing.
this.props.history.replace('/home')
window.localStorage.islogin = '1'
Copy the code
The authentication page is displayed
We need to authenticate on the login page. We let the login page judge when it is loaded. If it is logged in, we will jump to the home page, and to achieve this effect, we need to judge in useEffect() before the page is displayed.
useEffect(() = > {
let localStorage = window.localStorage
if (localStorage.islogin === '1') {
props.history.replace('/home')}})Copy the code
Login page full code
Use two useState() to record the account password entered by the user, which is then used for login authentication.
import React, { useEffect, useState } from 'react'
import './login.css'
function Login(props) {
useEffect(() = > {
let localStorage = window.localStorage
if (localStorage.islogin === '1') {
props.history.replace('/home')}})const [username, setUsername] = useState(' ')
const [password, setPassword] = useState(' ')
return (
<div className="login">
<h2>Welcome to the XXX blog area</h2>
<form className="form">
<div className="formItem">
<label htmlFor="username">User name:</label>
<input
type="text"
id="username"
value={username}
onChange={(e)= > setUsername(e.target.value)}
/>
</div>
<div className="formItem">
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(e)= > setPassword(e.target.value)}
/>
</div>
<div className="loginBtn" onClick={()= >HandleLogin ()} > to log in</div>
</form>
</div>
)
function handleLogin() {
if (username && password) {
props.history.replace('/home')
window.localStorage.islogin = '1'
alert('welcome! ')}else {
alert('Please enter username and password! ')}}}export default Login
Copy the code
The Home page
import React, { useState } from 'react'
import Comment from './comment'
import checkRole from './checkRole'
import './App.css'
function App(props) {
const [title, setTitle] = useState('Hello Hooks')
const [desc, setDesc] = useState(
'Did you know there was such a group? They have a dream, hard work, as a group of college students rookie, gave up the usual entertainment time, choose to learn together, grow together, the usual learning notes, summed up into the article, the purpose is very simple, I hope to help the rookie like them? Would you like to know more? Quick search wechat official account: newbies of Xiaohe Mountain, join them! '.)const [comments, setComments] = useState([
{
headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png'.time: new Date(2021.4.14.21.2.30),
nickName: 'Rookie'.detail: 'This is a team that's coming up with a series of articles, so let's look forward to their work! '.liked: true.likeNum: 23,}])const [text, setText] = useState(' ')
return (
<div className="App">
<span className="logout" onClick={handleLogout}>Log out</span>
<h2>{title}</h2>
<div className="desc">{desc}</div>
<div style={{ width: '100'}} % >
<p className="commentsTitle">comments</p>
{comments.map((item, index) => {
return (
<Comment key={item.time.getTime()} changeLike={()= >changeLike(index)} {... item} /> ) })}</div>
<div className="newComment">
<div style={{ display: 'flex' }}>
<img src="https://xhs-rookies.com/img/rookie-icon.png" className="" alt="" />
<textarea value={text} onChange={changeText} placeholder="Please enter a comment" />
</div>
<div className="submit" onClick={addComment}>published</div>
</div>
</div>
)
// Log out
function handleLogout() {
window.localStorage.islogin = '0'
props.history.replace('/login')}/ / change the text
function changeText(e) {
setText(e.target.value)
}
function changeLike(index) {
let newArray = [...comments]
letnewItem = { ... newArray[index] }if (newItem.liked) {
newItem.liked = false
newItem.likeNum -= 1
} else {
newItem.liked = true
newItem.likeNum += 1
}
newArray[index] = newItem
setComments(newArray)
}
function addComment() {
if(! text) { alert('Please enter message content')
return
}
let detail = text
setText(' ')
let newComment = {
headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png'.time: new Date(),
nickName: 'Rookie',
detail,
liked: false.likeNum: 0,
}
setComments([newComment, ...comments])
}
}
export default App
Copy the code
Components used
The comment component
This component is used to display user messages by data display.
import React from 'react'
import './comment.css'
function Comment(props) {
const { nickName, time, headPortrait, detail, liked, likeNum, changeLike } = props
return (
<div className="comment">
<div className="info">
<img src={headPortrait} alt="Avatar" />
<div>
<p className="nickname">{nickName}</p>
<p className="time">{getTime(time)}</p>
</div>
</div>
<div className="detail" style={{ marginBottom: '10px' }}>
{detail}
</div>
<div className="toolBox">
<span className={'likeBox'+ (liked ? 'like' : 'unlike')} onClick={changeLike}>
<span className="icon"> </span>
<span>{!!!!! likeNum && likeNum}</span>
</span>
<span className="share icon"> </span>
</div>
</div>
)
function getTime(time) {
const year = time.getFullYear()
const month = time.getMonth() + 1
const day = time.getDate()
const hour = String(time.getHours()).padStart(2.'0')
const minute = String(time.getMinutes()).padStart(2.'0')
const second = String(time.getSeconds()).padStart(2.'0')
return `${year}.${month}.${day} ${hour}:${minute}:${second}`}}export default Comment
Copy the code
conclusion
Which brings us to the end of the hooks exercise, which is a simple message function that also includes some use of hooks.
If you need to view the source code, you can view and download our open source library project github address
Next day forecast
That’s the end of which in this episode, we will bring you some interesting interview questions.