Come and join us!

“The Newbies of Little and Hill” provides technical information and a series of basic articles for front-end developers. For a better user experience, please move to our official website of Xiaoheshan beginners (https://xhs-rookies.com/) to learn, timely access to the latest articles.

“Code tailor”, if you are interested in our articles or would like to make some suggestions, please follow our official account “newbies of Xiaoheshan” at WeChat, and contact us. You can also view our articles on WeChat. Every suggestion or agreement is a great encouragement to us!

Practical case (four) : perfect message version login

We learned something new this time, so we need to revise the previous version.

First we need the login page and add authentication via Hoc (higher-order component). Add routing jump to complete the page.

Increase the routing

yarn add react-router-dom

Let’s start with React – Router

Modify routing configuration

We need to modify index.js, there was only one app.js in the previous index.js, and we added the configuration of routing to index.js.

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Switch>
        <Route path="/login" component={Login} />
        <Route path="/home" component={App} />
        <Redirect path="/" to="/login" exact />
      </Switch>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root'),
)

By default, we have the page point to the Login page.

The Login page

Login status maintenance

If we log in successfully, we should have a place to store the information of whether we log in successfully, so as to prepare for subsequent authentication. We use localStorage to do data persistence processing.

this.props.history.replace('/home')
window.localStorage.islogin = '1'

Authentication jump

We need to authenticate the login page. We will let the login page judge when the load is completed. If we have already logged in, then we will jump to the home home page.

  componentDidMount() {
    let localStorage = window.localStorage
    if (localStorage.islogin === '1') {
      this.props.history.replace("/home")
    }
  }

Eventually,

class Login extends PureComponent { componentDidMount() { let localStorage = window.localStorage if (localStorage.islogin === '1') { this.props.history.replace('/home') } } constructor(props) { super(props) this.state = { username: '', password: "', }} render() {return (<div className="login"> <h2> </h2> <form className="form"> <div className=" FormItem ">) {return (<div className=" FormItem "> </ div className="form"> <div className=" FormItem ">) <label htmlFor="username"> </label> <input type="text" id="username" value={this.state.username} onChange={(e) => { this.setState({ username: E.target.value})} / bb0 </div> <div className=" FormItem "> <label htmlFor="password"> </label> <input type="password" id="password" value={this.state.password} onChange={(e) => { this.setState({ password: Value})} / bb0 </div> <div className="loginBtn" onClick={() => {this.handleLogin()}} bb3 </div> </form> </div> ) } handleLogin() { if (this.state.username && this.state.password) { this.props.history.replace('/home') Window. The localStorage. Islogin = '1' alert (' welcome! ')} else {alert(' Please enter username and password! ') } } } export default Login

No components required

Last time we abstracted the InputCompoent input box component and the EvaluateCompoent list display component and placed them in the Component folder. We first placed these two components directly in app.js.

We just need to abstract a Comment component to add our thumb up functionality to the last EvaluateCompoent list display component, and we can thumb up each comment in the list.

So we changed the homepage app.js to the following:

import React, { PureComponent } from 'react' import Comment from './comment' import './App.css' class App extends PureComponent { Constructor () {super() this.state = {title: 'Hello React', desc: 'constructor() {super() this.state = {title: 'Hello React', They have a dream, hard work, as a group of college students rookie, gave up the usual entertainment time, choose to learn together, grow up together, the usual study notes, experience summed up for the article, the purpose is very simple, hope to help to them like rookie people? Do you want to know more? Quick search WeChat official account: Xiaoheshan newbies, join them! ', comments: [ { headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png', time: New Date(2021, 4, 14, 21, 2, 30), likeNum: 'This is a team that is about to launch a series of articles, let's look forward to their work together! ', likeNum: 23, }, ], text: '', } } render() { const { title, desc, comments, text } = this.state return ( <div className="App"> <h2>{title}</h2> <div className="desc">{desc}</div> <div style={{ width: <p className="commentsTitle"> comments </p> {comments.map((item,))} index) => { return ( <Comment key={item.time.getTime()} changeLike={() => { this.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 ={(e) => this.changeText(e)} placeholder=" submit" /> </div> <div className="submit" onClick={(e) => { </div> </div> </div>)} changeText(e) {this.setState({text: e.target.value }) } changeLike(index) { let newArray = [...this.state.comments] let newItem = { ... newArray[index] } if (newItem.liked) { newItem.liked = false newItem.likeNum -= 1 } else { newItem.liked = true newItem.likeNum += 1 } newArray[index] = newItem this.setState({ comments: newArray, }) } addComment() { if (! This.state.text) {alert(' Please enter message content ') return} let detail = this.state.text this.setState({text: '' }) let newComment = { headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png', time: new Date(), nickName: } this. SetState ({comments: [newComment, ...this.state.comments], }) } } App.propTypes = {} export default App

The home page to modify

The home page to

Here we also need to authenticate, that is, if we type home directly in the browser, if it is not logged in, we need to let it jump to the login login page.

Can we use the same time as login, after the load is complete, judge and jump?

  componentDidMount() {
    let localStorage = window.localStorage
    if (localStorage.islogin === '1') {
      this.props.history.replace("/home")
    }
  }

In fact, there is a problem here. If we jump directly after the completion of loading judgment, whether every page should be added?

But this authentication is actually a general function, if there is a personal information page, is it also a need for such a function?

High-level component authentication

We use high-order components for authentication, then every page if you need authentication, only need to be wrapped by high-order components.

import React from 'react' import { Redirect } from 'react-router-dom' export default function checkRole(WrapperComponent) { let localStorage = window.localStorage return (props) => { if (localStorage.islogin === '1') { return <WrapperComponent {... props} /> } else { return <Redirect to="/" /> } } }

Then we wrapped the Home page (app.js)

export default checkRole(App)

Logout option

After we log in successfully, then we naturally need to add the logout option on the home page, and then log out, and then enter the home page again will be judged to jump to the login page.

  handleLogout() {
    window.localStorage.islogin = '0'
    this.props.history.replace("/login")
  }

The final main page looks like this:

import React, { PureComponent } from 'react' import Comment from './comment' import checkRole from './checkRole' import './App.css' Class App extends PureComponent {constructor() {super() this.state = {title: 'Hello React', desc: '. They have a dream, hard work, as a group of college students rookie, gave up the usual entertainment time, choose to learn together, grow up together, the usual study notes, experience summed up for the article, the purpose is very simple, hope to help to them like rookie people? Do you want to know more? Quick search WeChat official account: Xiaoheshan newbies, join them! ', comments: [ { headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png', time: New Date(2021, 4, 14, 21, 2, 30), likeNum: 'This is a team that is about to launch a series of articles, let's look forward to their work together! ', likeNum: 23, }, ], text: '', } } render() { const { title, desc, comments, text } = this.state return ( <div className="App"> <span className="logout" onClick={() => { this.handleLogout() }} > </span> <h2>{title}</h2> <div className="desc">{desc}</div> <div style={{width: 0; <p className="commentsTitle"> comments </p> {comments.map((item,))} index) => { return ( <Comment key={item.time.getTime()} changeLike={() => { this.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 ={(e) => this.changeText(e)} placeholder=" submit" /> </div> <div className="submit" onClick={(e) => { Published this. AddComment ()}} > < / div > < / div > < / div >)} handleLogout () {window. LocalStorage. Islogin = '0' this.props.history.replace('/login') } changeText(e) { this.setState({ text: e.target.value }) } changeLike(index) { let newArray = [...this.state.comments] let newItem = { ... newArray[index] } if (newItem.liked) { newItem.liked = false newItem.likeNum -= 1 } else { newItem.liked = true newItem.likeNum += 1 } newArray[index] = newItem this.setState({ comments: newArray, }) } addComment() { if (! This.state.text) {alert(' Please enter message content ') return} let detail = this.state.text this.setState({text: '' }) let newComment = { headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png', time: new Date(), nickName: } this. SetState ({comments: [newComment, ...this.state.comments], }) } } App.propTypes = {} export default checkRole(App)

conclusion

This is the end of the React Actioncase. It’s a simple message case, but it covers a lot of knowledge, from HTML to scaffolding.

Home authentication has been added, PropTypes have been used to check incoming data for compliance, and Hoc (higher-order components) have been used to add common component functionality.

Instant preview

We recommend a CodeSanBox for quick online access to current real-life cases.

CodeSandBox

Next day forecast

Now that we have learned the basics of React, in the next section we will move towards higher peaks.