码迷,mamicode.com
首页 > 其他好文 > 详细

【react】react-reading-track

时间:2019-06-04 17:49:28      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:info   reads   初始   hat   list   outer   map   pos   filter   

这是一个很有趣的图书阅读demo
技术图片
先放github地址:https://github.com/onlyhom/react-reading-track
我觉得这个博主的项目很有意思呢
我们一起看看代码啊
技术图片
没有中间件对数据进行处理

//index.js
//这个是根index.js文件引用了app.vue
import React from 'react'
import ReactDOM from 'react-dom'
import {BrowserRouter} from 'react-router-dom'
import App from './App'
import './index.css'

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

关于search页面
技术图片

//src\BooksAPI.js

const api = "https://reactnd-books-api.udacity.com"


// Generate a unique token for storing your bookshelf data on the backend server.
let token = localStorage.token
if (!token)
  token = localStorage.token = Math.random().toString(36).substr(-8)

const headers = {
  'Accept': 'application/json',
  'Authorization': token
}

export const get = (bookId) =>
  fetch(`${api}/books/${bookId}`, { headers })
    .then(res => res.json())
    .then(data => data.book)

export const getAll = () =>
  fetch(`${api}/books`, { headers })
    .then(res => res.json())
    .then(data => data.books)

export const update = (book, shelf) =>
  fetch(`${api}/books/${book.id}`, {
    method: 'PUT',
    headers: {
      ...headers,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ shelf })
  }).then(res => res.json())

export const search = (query) =>
  fetch(`${api}/search`, {
    method: 'POST',
    headers: {
      ...headers,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ query })
  }).then(res => res.json())
    .then(data => data.books)
//src\Book.js
import React, {Component} from 'react'
import {Route, Link} from 'react-router-dom'

class Book extends Component {

  changeShelf(shelf) {
    this.props.moveBook(this.props.book, shelf)
  }

  render(){

    const {book} = this.props

    return(
        <div className="book">
          <div className="book-top">
            <div className="book-cover" style={{ width: 128, height: 193, backgroundImage: `url(${book.imageLinks !== undefined ? book.imageLinks.thumbnail: ''})` }}></div>
            <div className="book-shelf-changer">
              <select value={book.shelf!== undefined ? book.shelf : 'none'} onChange={(event) => this.changeShelf(event.target.value)}>
                <option value="none" disabled>移动到...</option>
                <option value="currentlyReading">正在读</option>
                <option value="wantToRead">想读</option>
                <option value="read">已读</option>
                <option value="none">无</option>
              </select>
            </div>
          </div>
          <div className="book-title">{book.title}</div>
          <div className="book-authors">{book.authors}</div>
        </div>
      )
  }

}

export default Book
//src\SearchPage.js
import React, {Component} from 'react'
import {Route, Link} from 'react-router-dom'
import Book from './Book'
import * as BooksAPI from './BooksAPI'

class SearchPage extends Component {

  state = {
    searchString: '',
    booksData: []
  }

  changeSearchString = (searchString) => {
    if (!searchString) {
    // 输入为空时,状态设置为初始状态;
      this.setState({searchString: '', booksData: []})
    } else {
      // 输入不为空时,使用BookAPI的search()异步更新状态数据
      this.setState({ searchString: searchString.trim() })
      BooksAPI.search(searchString).then((booksData) => {
        console.log(booksData);
        if (booksData.error) {
          booksData = [];
        }
        booksData.map(book => (this.props.booksData.filter((oneShelfBook) => oneShelfBook.id === book.id)
        .map(oneShelfBook => book.shelf = oneShelfBook.shelf)));
        this.setState({booksData})
      })
    }
  }

  render(){
    var booksArr = ['name1','name2','name3'];

    return(
          <div className="search-books">
            <div className="search-books-bar">
              <Link className="close-search" to="/">Close</Link>
              <div className="search-books-input-wrapper">
                {/*
                  NOTES: The search from BooksAPI is limited to a particular set of search terms.
                  You can find these search terms here:
                  https://github.com/udacity/reactnd-project-myreads-starter/blob/master/SEARCH_TERMS.md

                  However, remember that the BooksAPI.search method DOES search by title or author. So, don't worry if
                  you don't find a specific author or title. Every search is limited by search terms.
                */}
                <input type="text" placeholder="通过书名或作者名来查" onChange={(event)=> this.changeSearchString(event.target.value) }/>

              </div>
            </div>
            <div className="search-books-results">
              <ol className="books-grid">
                {
                  this.state.booksData.map((book,index)=>(
                   <li key={index}>
                    <Book
                      key={book.id}
                      book={book}
                      moveBook={this.props.moveBook}
                    />
                    </li>
                  ))
                }

              </ol>
            </div>
          </div>
    )
  }
}

export default SearchPage

技术图片

//src\ListBooks.js
import React, {Component} from 'react'
import {Route, Link} from 'react-router-dom'
import Book from './Book'

class ListBooks extends Component {
  render(){
    var titleArr = ["currentlyReading", "wantToRead", "read"];
    var booksArr = ['name1','name2','name3'];
    return(
          <div className="list-books">
            <div className="list-books-title">
              <h1>MyReads</h1>
            </div>

            <div className="list-books-content">
              <div>
                {
                  titleArr.map((booksort,index)=>(
                    <div className="bookshelf" key={index}>
                      <h2 className="bookshelf-title">{ booksort }</h2>
                      <div className="bookshelf-books">
                        <ol className="books-grid">
                          {
                            this.props.booksData.filter(book => book.shelf == booksort)
                            .map((book,index)=>(
                             <li key={index}>
                              <Book 
                                key={book.id}
                                book={book}
                                moveBook={this.props.moveBook}
                              />
                              </li>
                            ))
                          }

                        </ol>
                      </div>
                    </div>

                    ))
                }


              </div>
            </div>
            <div className="open-search">
               <Link to="/searchpage">Add a book</Link>
            </div>
          </div>
          
    )
  }
}

export default ListBooks

代码和编程思想都挺有意思的

【react】react-reading-track

标签:info   reads   初始   hat   list   outer   map   pos   filter   

原文地址:https://www.cnblogs.com/smart-girl/p/10974795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!