react练习,根据关键字查询用户

一、项目中需要请求数据,装axios包

npm install axios --save

 

二、拆分组件

App

      * state: searchName/string

Search

         * props: setSearchName/func

List

         * props: searchName/string

         * state: firstView/bool, loading/bool, users/array, errMsg/string

 

三、知识点

1、componentWillReceiveProps 当组件接收到新的props时候调用,他有一个参数props

2、axios 数据请求

四、源码

入口文件index.js

import React from 'react'
import { render } from 'react-dom'

import App from './components/app'
import './index.css'

render(<App />, document.getElementById('root'))

应用组件app.jsx

import React from 'react'
import Search from './search'
import UserList from './user-list'

export default class App extends React.Component {

  state = {
    searchName: ''
  }

  refreshName = (searchName) => this.setState({searchName})

  render() {
    return (
      <div className="container">
        <section className="jumbotron">
          <h3 className="jumbotron-heading">Search Github Users</h3>
          <Search refreshName={this.refreshName}/>
        </section>
        <UserList searchName={this.state.searchName}/>
      </div>
    )
  }

}

搜索组件search.jsx

/**
 * 上部的搜索模块
 */
import React, {Component} from 'react'
import PropTypes from 'prop-types'

class Search extends Component {

  static propTypes = {
    refreshName: PropTypes.func.isRequired
  }

  search = () => {
    var name = this.nameInput.value
    this.props.refreshName(name)
  }

  render() {
    return (
      <div>
        <input type="text" placeholder="enter the name you search"
               ref={(input => this.nameInput = input)}/>
        <button onClick={this.search}>Search</button>
      </div>
    )
  }
}

export default Search

列表组件user-list.jsx

/**
 * 下部的用户列表模块
 */
import React from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'

class UserList extends React.Component {

  static propTypes = {
    searchName: PropTypes.string.isRequired
  }

  state = {
    firstView: true,
    loading: false,
    users: null,
    error: null
  }

//componentWillReceiveProps 组件将要接收到新的props时候调用,async 参考:https://www.cnblogs.com/cckui/p/10444246.html
  async componentWillReceiveProps(nextProps)  {//指定了新的searchName,需要发请求请求数据
    let searchName = nextProps.searchName
    console.log('发送ajax请求', searchName)
    const url = `https://api.github.com/search/users?q=${searchName}`
    //更新请求状态,请求中
    this.setState({ firstView: false, loading: true })

    // 使用axios库
    axios.get(url)
      .then((response) => {
        console.log(response)
        this.setState({ loading: false, users: response.data.items })
      })
      .catch((error)=>{
        // debugger
        console.log('error', error.response.data.message, error.message)
        this.setState({ loading: false, error: error.message })
      })
//异步请求 例子
    try {
      const result = await axios.get(url)
      this.setState({ loading: false, users: result.data.items })
    } catch(err) {
      // debugger
      console.log('----', err.message)
    }
  }

  render () {

    if (this.state.firstView) {
      return <h2>Enter name to search</h2>
    } else if (this.state.loading) {
      return <h2>Loading result...</h2>
    } else if (this.state.error) {
      return <h2>{this.state.error}</h2>
    } else {
      return (
        <div className="row">
          {
            this.state.users.map((user) => (
              <div className="card" key={user.html_url}>
                <a href={user.html_url} target="_blank">
                  <img src={user.avatar_url} style={{width: '100px'}} alt='user'/>
                </a>
                <p className="card-text">{user.login}</p>
              </div>
            ))
          }
        </div>
      )
    }
  }
}

export default UserList

 

代码下载   https://download.csdn.net/download/chunxiaqiudong5/12062984

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一个简单的示例代码,演示如何使用React和TypeScript实现关键字模糊查询接口的联通。 首先,我们需要安装必要的依赖项。打开终端,进入项目目录,执行以下命令: ``` npm install react react-dom @types/react @types/react-dom axios @types/axios ``` 其中,`react`和`react-dom`是React框架的核心依赖,`@types/react`和`@types/react-dom`是React框架的TypeScript类型定义文件,`axios`是一个基于Promise的HTTP客户端,用于发送Ajax请求,`@types/axios`是axios库的TypeScript类型定义文件。 接下来,在项目中创建一个名为`SearchBox`的组件,用于输入关键字,并向服务器发送请求: ```tsx import React, { useState } from "react"; import axios from "axios"; type SearchResult = { id: number; name: string; description: string; }; const SearchBox: React.FC = () => { const [query, setQuery] = useState<string>(""); // 输入框的值 const [results, setResults] = useState<SearchResult[]>([]); // 搜索结果 const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { setQuery(event.target.value); }; const handleSearch = async () => { const response = await axios.get<SearchResult[]>( `/api/search?q=${encodeURIComponent(query)}` ); setResults(response.data); }; return ( <div> <input type="text" value={query} onChange={handleInputChange} /> <button onClick={handleSearch}>搜索</button> <ul> {results.map((result) => ( <li key={result.id}> <h3>{result.name}</h3> <p>{result.description}</p> </li> ))} </ul> </div> ); }; export default SearchBox; ``` 在上面的代码中,我们定义了一个名为`SearchBox`的函数式组件,它包含一个输入框、一个搜索按钮和一个无序列表。当用户输入关键字并点击搜索按钮时,`handleSearch`函数将会发送一个GET请求到`/api/search`接口,并将查询字符串作为参数传递给服务器。服务器将返回一个JSON数组,包含匹配的搜索结果。我们使用`axios`库发送请求并处理响应。一旦收到响应,我们将搜索结果存储在`results`状态中,并使用`map`函数将它们渲染到无序列表中。 现在,让我们在项目中创建一个名为`server.ts`的文件,用于模拟服务器端的行为: ```ts import express from "express"; type SearchResult = { id: number; name: string; description: string; }; const data: SearchResult[] = [ { id: 1, name: "JavaScript", description: "一门流行的脚本语言", }, { id: 2, name: "TypeScript", description: "JavaScript的超集,具有强类型和面向对象的特性", }, { id: 3, name: "React", description: "一款流行的前端UI框架", }, { id: 4, name: "Angular", description: "一款流行的前端框架", }, ]; const app = express(); app.get("/api/search", (req, res) => { const q = req.query.q as string; const results = data.filter((item) => item.name.toLowerCase().includes(q.toLowerCase()) ); res.json(results); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is listening on port ${port}`); }); ``` 在上面的代码中,我们使用`express`库创建了一个名为`app`的Web应用程序,它包含一个GET路由,用于处理`/api/search`请求。当收到请求后,服务器将会读取查询字符串中的`q`参数,并使用`filter`函数从`data`数组中过滤出匹配的结果。最后,服务器将结果作为JSON响应发送回客户端。在这个示例中,我们使用了一个静态的搜索结果,实际应用中,我们可以使用数据库或其他数据源来进行搜索。 最后,在项目中的`index.tsx`文件中,我们可以渲染`SearchBox`组件: ```tsx import React from "react"; import ReactDOM from "react-dom"; import SearchBox from "./SearchBox"; ReactDOM.render(<SearchBox />, document.getElementById("root")); ``` 现在,我们可以启动应用程序并测试搜索功能了。在终端中执行以下命令: ``` npm start ``` 打开浏览器,访问`http://localhost:3000`,输入关键字并点击搜索按钮,即可看到匹配的搜索结果。 这就是使用React和TypeScript实现关键字模糊查询接口的联通的示例代码。希望能对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值