This is the 28th day of my participation in the August Challenge

📢 Hello everyone, I am Xiao Cheng, a prospective sophomore front-end enthusiast

📢 This article is a study note for the GitHub search example in React

📢 Thank you very much for reading

📢 May you be true to yourself and love life

The introduction

This article introduces Github search in React learning. This case mainly involves Axios sending requests, data rendering, and some intermediate alternate effects

Personally, after finishing the TodoList case, this case will be very easy, but with the addition of an idea to realize the Loading effect and the improvement of some small details, I feel that it is very good to practice

Implement static components

As in the previous TodoList case, we need to implement the static component first. Before implementing the static component, we need to split the component, the component of this page, into the following two components: the first component is Search and the second component is List

Next we need to split the pre-written static pages into components

Note:

  1. Class needs to be changed to className
  2. The style value needs to be in double curly braces

Most importantly, the IMG tag must have an Alt attribute indicating when the image fails to load.

At the same time, the A tag should have a rel=”noreferrer” attribute, otherwise there will be a lot of warnings

2. Axios sends the request

After implementing the static component, we need to send a request to Github to get the appropriate user information

However, due to multiple requests in a short period of time, the request may not return results, etc., so we used a pre-built local server

We just start the server and send a request to this address

This request type is a GET request, and we need to pass in a search keyword to request data

We first need to get the value in the input box after the user clicks the search button

Add the ref attribute to the input tag where you want to fire the event

 <input ref={c= > this.keyWordElement = c} type="text" placeholder="Enter keywords and click search." />
Copy the code

We can get the current node, which is the input box, using the this.keyWordElement property

We can get the value in the current input box by using the value

/ / search callbacks
const { keyWordElement: { value: keyWord } } = this
Copy the code

Here we use a continuous deconstruction of the assignment, and finally change the value to keyWord to make it easier to identify

Once we get the keyWord value, we need to send the request

axios.get(`http://localhost:3000/api1/search/users? q=${keyWord}`).then(
    response= > {
        this.props.updateAppState({ isLoading: false.users: response.data.items })
    },
    error= > {
        this.props.updateAppState({ isLoading: false.err: error.message })
    }
)
Copy the code

We pass the parameter by attaching the keyWord to the request address to get the relevant data

There’s a cross-domain problem here, because I’m standing on port 3000 and sending requests to port 5000

Therefore we need to configure the proxy to solve the cross-domain problem. We need to add the proxy enabled flag/API1 before requesting the address

// setupProxy.js
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
    app.use(
        proxy('/api1', {
            target: 'http://localhost:5000'.changeOrigin: true.pathRewrite: {
                '^/api1': ' '}}}))Copy the code

So we can successfully get the data

Third, render data

Once we have the data, we need to analyze it and render it to the page

The important point is that the number of users we get is dynamic, so we need to iterate to achieve it

At the same time, our data currently exists in the Search component, and we need to use it in the List component, so we need a Search component to pass a function to realize the child to transfer data to the parent, and then pass data to the List component through the App component to get data

users.map((userObj) = > {
  return (
    <div key={userObj.id} className="card">
      <a rel="noreferrer" href={userObj.html_url} target="_blank">
        <img alt="avatar" src={userObj.avatar_url} style={{ width: '100px' }} />
      </a>
      <p className="card-text">{userObj.login}</p>
    </div>)})Copy the code

So here we’re going to iterate over the data that we’re going to return with a map, adding cards in a loop

Add some user information to it as well

Fourth, increase interaction

This is more than half the way through, but there seems to be less interaction

  • Loading effect during loading
  • Welcome in the List component when you first enter the page
  • An error message should be displayed when reporting an error

All these indicate that we cannot simply render user data directly. We need to add some judgments, such as when to render data, when to render loading, and when to render ERR

First we need to add some state that tells us what to render, like

  • usingisFristTo determine whether the page is started for the first time, the initial value giventrue, click search and change tofalse
  • usingisLoadingTo check whether the Loading animation should be displayedfalse“After clicking searchtrueAfter getting the datafalse
  • usingerrTo determine whether to render error message, when error message, fill in the error message, the initial valueTo empty
state = { users: [].isFirst: true.isLoading: false.err: ' ' }
Copy the code

So we need to change the way I pass the data, and use the update state method, so that we receive a state object to update the data, so that we don’t have to specify when to update what, so that we can reduce a lot of unnecessary function declarations, right

At the same time, when the App component passes data to the List component, we can use the method of deconstructing the assignment, which can reduce the amount of code

// App.jsx
// Receive a status object
updateAppState = (stateObj) = > {
    this.setState(stateObj)
}
<Search updateAppState={this.updateAppState} />
<List {. this.state} / >
Copy the code

So we just need to judge the values of these states in the List component to display them

// List/index.jsx
// Object destruct
const { users, isFirst, isLoading, err } = this.props
/ / determine
{
  isFirst ? <h2>Welcome to use, enter the keyword, click search</h2> :
    isLoading ? <h2>Loading...</h2> :
      err ? <h2 style={{ color: 'red' }}>{err}</h2> :
        users.map((userObj) = > {
          return (
           // Render blocks of data
           // In order to reduce the amount of code, I will not paste)})}Copy the code

We need to check if it’s the first time, then check if it’s loading, then check if there’s an error, and then render the data

Our status update is implemented in the Search component, and we need to change isFirst to false and isLoading to true before the data is returned after clicking Search

After receiving data, we can change isLoading to false

The above is the Github search case implementation process, the final effect picture


The front end road is very long, today I will be a sophomore! Come on!!

Thank you very much for reading, welcome to put forward your opinion, if you have any questions, please point out, thank you! 🎈