React电影列表项目

1 构建项目基本结构

在这里插入图片描述
main.js

//这是项目的js打包入口文件
import React from 'react'
import ReactDom from 'react-dom'

import App from './App.jsx'

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

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <!-- 这是一个容器,将来 使用 react 渲染的虚拟DOM,都会放到这个容器中 -->
  <div id="app"></div>
 
</body>

</html>

app.jsx

//这是项目的根组件
import React from 'react'

export default class App extends React.Component{
    constructor(props){
        super(props)

        this.state={

        }
    }
    render(){
        return<div>
            <h1>这是项目的根组件</h1>
        </div>
    }
}

在这里插入图片描述

2 完成首页基本布局

导入路由组件
App.jsx

import {HashRouter,Route,Link} from 'react-router-dom'

导入需要的Ant Design组件
App.jsx

import { Layout, Menu } from 'antd';
const { Header, Content, Footer } = Layout;

复制官网的layout的代码 并修改样式

export default class App extends React.Component{
    constructor(props){
        super(props)

        this.state={

        }
    }
    render(){
       return<HashRouter>            
                <Layout className="layout" style={{height:"100%"}}>

                {/*Header头部区域  */}
                <Header>
                <div className="logo" />
                <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['1']}>
                    <Menu.Item key="1">首页</Menu.Item>
                    <Menu.Item key="2">电影</Menu.Item>
                    <Menu.Item key="3">关于</Menu.Item>
                </Menu>
                </Header>
                {/* 中间的内容区域 */}
                <Content style={{ backgroundColor:'#fff'}}>
                <div className="site-layout-content">Content</div>
                </Content>
                {/*  */}
                <Footer style={{ textAlign: 'center' }}>个人电影 ©2020 Created </Footer>
            </Layout>
       </HashRouter>
    }
}

将app组件的高度改为100%
index.html

<div id="app" style="height:100%;"></div>

新建一个scss文件 设置导航栏图标样式

// 由于在webpack.config.js配置了.scss文件模块化(.css不能配置模块化)自己的样式要写成.scss
//根据antd官方文档设置样式
 .logo {
        width: 120px;
        height: 31px;
        background: rgba(255, 255, 255,1) url('../img/logo.png');
        margin: 16px 24px 16px 0;
        float: left;
        background-size: cover;
        border-radius: 6px;
    }

导入模块化的样式
app.jsx

//导入模块化的样式
import styles from './css/app.scss'

修改Header内div标签的className

 {/*Header头部区域  */}
                <Header>
                <div className={styles.logo} />

在这里插入图片描述

3 使用路由切换组件页

创建HomeContainer.jsx,AboutContainer.jsx,MovieContainer.jsx
三个组件
HomeContainer.jsx

import React from 'react'


export default class HomeContainer extends React.Component{
    constructor(props){
        super(props)
        this.state={

        }
    }
    render(){
        return<div>
            <h1>首页</h1>
        </div>
    }
}

App.jsx

 <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['1']}>
                    <Menu.Item key="1"><Link to="/home">首页</Link></Menu.Item>
                    <Menu.Item key="2"><Link to="/movie">电影</Link></Menu.Item>
                    <Menu.Item key="3"><Link to="/about">关于</Link></Menu.Item>
                </Menu>
//导入路由相关的组件
import HomeContainer from './Componebt/HomeContainer.jsx'
import AboutContainer from './Componebt/AboutContainer.jsx'
import MovieContainer from './Componebt/MovieContainer.jsx'
  {/* 中间的内容区域 */}
                <Content style={{ backgroundColor:'#fff'}}>
                   <Route path="/home" component={HomeContainer}></Route>
                   <Route path="/Movie" component={MovieContainer}></Route>
                   <Route path="/About" component={AboutContainer}></Route>
                </Content>

在这里插入图片描述
刷新页面时保持上一次的选中状态

  {/* 根据路径中的hash值来设置defaultSelect值 
                    split:按/切割 并得到一个数组 */}
                <Menu theme="dark" mode="horizontal" defaultSelectedKeys={[window.location.hash.split('/')[1]]}>
                    <Menu.Item key="home"><Link to="/home">首页</Link></Menu.Item>
                    <Menu.Item key="movie"><Link to="/movie">电影</Link></Menu.Item>
                    <Menu.Item key="about"><Link to="/about">关于</Link></Menu.Item>
                </Menu>

4 完成电影页面的基本结构

使用antd的Layout的侧边栏并修改
按需导入

import { Layout, Menu} from 'antd';
const { Content, Sider } = Layout;
  return <Layout className="site-layout-background" style={{height:"100%",backgroundColor:"#fff" }}>
        <Sider className="site-layout-background" width={200} style={{backgroundColor:"#fff"}}>
          <Menu
            mode="inline"
            defaultSelectedKeys={['1']}
           
            style={{ height: '100%' }}
          >
           
              <Menu.Item key="1">正在热映</Menu.Item>
              <Menu.Item key="2">即将上映</Menu.Item>
              <Menu.Item key="3">top250</Menu.Item>
              
          </Menu>
        </Sider>
        <Content style={{ padding:"10px"}}>Content</Content>
      </Layout>

在这里插入图片描述

5 改造电影页面中左侧边栏每一项的路由

MovieContainer.jsx

<Menu.Item key="1"><Link to="/movie/in_theaters/1">正在热映</Link></Menu.Item>
              <Menu.Item key="2"><Link to="/movie/coming_soon/1">即将上映</Link></Menu.Item>
              <Menu.Item key="3"><Link to="/movie/top250/1">top250</Link></Menu.Item>

修改App.jsx中movie的Link 使其一进入电影页面默认显示/movie/in_theaters/1所对应的页面

<Menu.Item key="movie"><Link to="/movie/in_theaters/1">电影</Link></Menu.Item>

创建MovieList.jsx

import React from 'react'


export default class MovieList extends React.Component{
    constructor(props){
        super(props)
        this.state={

        }
    }
    render(){
        return<div>
            <h1>MovieList----{this.props.match.params.type}----{this.props.match.params.page}</h1>
        </div>
    }
}

MovieContainer.jsx

  <Content style={{ padding:"10px"}}>
          {/*只需要放一个route匹配上面所有的路由规则
             因为右侧三个组件只需要对应这一个子组件 结构都相同 只是显示的数据不同 不需要创建3个组件 */}
             {/* 在匹配路由规则的时候 这里提供了两个参数 
                 如果想要从路由规则中提取参数 需要使用this.props.match.params.type */}
            <Route path="/movie/:type/:page" component={MovieList}></Route>
        </Content>

在这里插入图片描述

6 获取数据并渲染

定义所需的数据对象
MovieList.jsx

this.state={
            movies:[],//电影列表
            nowPage:parseInt(props.match.params.page)||1,//当前展示第几页的数据
            pageSize:14,//每页显示多少条数据
            total:0,//当前电影分类下 总共有多少条数据
            isloading:true, //数据是否正在加载如果为true表示正在加载数据

定义渲染列表的方法 在其中实现加载的动态效果

 renderList(){
        if(this.state.isloading){      
            {/* 使用antd的spin UI组件 */}
            return<Spin tip="Loading...">
               <Alert
               message="正在请求电影列表"
               description="精彩内容,马上呈现..."
               type="info"
               />
           </Spin>
        }else{//加载完成
            return<h1>加载完成</h1>
        }
    }

在render中调用

render(){
        return<div>
           { this.renderList()}
        </div>
    }

在这里插入图片描述
获取数据

loadMovieListByTypeAndPage=()=>{

        // 豆瓣接口文档https://douban-api-docs.zce.me/movie
        // 如果fetch有跨域限制 可以安装fatch-jsop 的第三方包 导入后 使用.fetchJsonp
        fetch("https://douban.uieee.com/v2/movie/in_theaters")
        .then(response=>{
            return response.json()
        })
        .then(data=>{
            console.log(data)
        })
    }
    //在React中,我们可以使用fetchAPI来获取数据 是基于promise封装的

在componentWillUpdate()中调用

this.loadMovieListByTypeAndPage()

根据电影类型和电影的页码获取电影数据

在this.state定义movieType保存要获取的电影的类型

movieType:props.match.params.type
loadMovieListByTypeAndPage=()=>{

        //开始获取数据的索引
        const start=this.state.pageSize*(this.state.nowPage-1)

        //模板字符串拼接 根据左侧边栏所选择的电影类型来获取数据
        //根据api文档 要传入start和count值
        const url=`https://douban.uieee.com/v2/movie/${this.state.movieType}?start=${start}&count=${this.state.pageSize}`

        // 豆瓣接口文档https://douban-api-docs.zce.me/movie
        // 如果fetch有跨域限制 可以安装fatch-jsop 的第三方包 导入后 使用.fetchJsonp
        fetch(url)
        .then(response=>{
            return response.json()
        })
        .then(data=>{        
            this.setState({
                isloading:false,//把loading效果隐藏
                movies:data.subjects,//为电影列表重新赋值
                total:data.total//把总条数 保存到state上
            })         
        })
        
       
    }

新建一个电影列表子组件
MovieItem

import React from 'react'

export default class MovieItem extends React.Component{
    constructor(props){
        super(props)

        this.state={

        }
    }
    render(){
        return<div>
            <h4>电影名称:{this.props.title}</h4>
        </div>
    }
}

导入 并求改renderList中的return值
MovieList.jsx

import MovieItem from './sub/MovieItem.jsx'
//渲染电影列表的方法
    renderList(){
        if(this.state.isloading){      
            {/* 使用antd的spin */}
            return<Spin tip="Loading...">
               <Alert
               message="正在请求电影列表"
               description="精彩内容,马上呈现..."
               type="info"
               />
           </Spin>
        }else{//加载完成
            return<div>
                {this.state.movies.map((item,i)=>{
                    return<MovieItem {...item} key={i}></MovieItem>
                })}
            </div>
        }
    }

注意:如果接口有次数限制 可以将请求回的数据保存到json文件中使用setTimeout来模拟请求数据加载的延迟时间 之后可以可以使用json文件中的data来渲染

const data=require('./test_data/in_theaters.json')
        setTimeout(()=>{
            this.setState({
                isloading:false,//把loading效果隐藏
                movies:data.subjects,//为电影列表重新赋值
                total:data.total//把总条数 保存到state上
            })
        },1000)

在这里插入图片描述
渲染电影列表 并美化样式

注意:这里获取的图片路径自动为.jpg格式 而接口中提供的图片路径为.webp格式 所以会导致访问图片路径和接口中的不一致而导致图片无法加载
解决:在图片标签中将图片路径末尾.jpg替换成.webp

movieItem.jsx

import React from 'react'

import style from '../../css/item.scss'

export default class MovieItem extends React.Component{
    constructor(props){
        super(props)

        this.state={

            
        }
    }
    componentWillMount(){
           
    }
    render(){
        return<div className={style.box}>
            <img src={this.props.images.small.replace('.jpg','.webp')} className={style.img}></img>
            <h4>电影名称:{this.props.title}</h4>
            <h4>上映年份:{this.props.year}</h4>
            <h4>电影类型:{this.props.genres.join(',')}</h4>
        </div>
    }
    
}

item.scss

.box{
    border: 1px solid #ddd;
    text-align: center;
    width: 170px;
    margin: 3px;
    box-shadow: 0 0 6px #ddd;
    padding: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    .img{
        width: 100px;
        height: 140px;
    }

    &:hover{
        opacity: 0.9;
        // scale 放大
        transform: rotateZ(1deg) scale(1.03);
    }
}

movieList

return<div style={{display:'flex',flexWrap:'wrap'}}>
                {this.state.movies.map((item,i)=>{
                    return<MovieItem {...item} key={i}></MovieItem>
                })}
            </div>

注意:这里在加载图片的时候会出现图片无法显示 出现get <…图片路径> 403的错误 是因为图片防盗链的问题
解决:在index.html加上

<meta name="referrer" content="no-referrer" />

在这里插入图片描述
在图片底部添加评分控件

导入antd的评分控件

import { Rate } from 'antd';

要将获取的评分除以二 因为只有5颗星

 return<div className={style.box}>
            <img src={this.props.images.small.replace('.jpg','.webp')} className={style.img}></img>
            <h4>电影名称:{this.props.title}</h4>
            <h4>上映年份:{this.props.year}</h4>
            <h4>电影类型:{this.props.genres.join(',')}</h4>
            {/* 使用antd的评分控件 */}
            <Rate disabled defaultValue={this.props.rating.average/2} />
        </div>

在这里插入图片描述

7 点击不同分类加载

//组件将要接收的新属性
    //每当地址栏变化的时候 重置state的参数项 重置完毕之后 可以重新发起请求
    componentWillReceiveProps(nextProps){
        this.setState({
            isloading:true,//重新渲染电影数据
            nowPage:parseInt(nextProps.match.params.page)||1,
            movieType:nextProps.match.params.type,
            
        },function(){
            //要通过回调函数来调用 不可以在外面直接调用 因为是异步执行的
            this.loadMovieListByTypeAndPage()
        })
    }

在这里插入图片描述
刷新列表 保存左侧tap栏之前的选中状态

修改Layout控件中Menu.Item的key值 设置 defaultSelectedKeys的值
MovieContainer.jsx

<Sider className="site-layout-background" width={200} style={{backgroundColor:"#fff"}}>
          <Menu
            mode="inline"
            defaultSelectedKeys={[window.location.hash.split('/')[2]]}
           
            style={{ height: '100%' }}
          >
           
              <Menu.Item key="in_theaters"><Link to="/movie/in_theaters/1">正在热映</Link></Menu.Item>
              <Menu.Item key="coming_soon"><Link to="/movie/coming_soon/1">即将上映</Link></Menu.Item>
              <Menu.Item key="top250"><Link to="/movie/top250/1">top250</Link></Menu.Item>
              
          </Menu>
        </Sider>

8 实现分页功能和根据不同页面加载数据

导入antd提供的分页控件

import { Pagination } from 'antd';

在renderList的return中添加该控件
MovieList.jsx

return<div>
                <div style={{display:'flex',flexWrap:'wrap'}}>
                    {this.state.movies.map((item,i)=>{
                        return<MovieItem {...item} key={i}></MovieItem>
                    })}
                </div>
                {/* 使用antd的分页控件 根据api文档设置 defaultCourrent:当前所在页数
                    total:数据总条数 pageSize:每页显示多少条数据*/}
                <Pagination defaultCurrent={this.state.nowPage} 
                            total={this.state.total} 
                            pageSize={this.state.pageSize}
                            onChange={this.pageChanged}/>
            </div>

定义pageChanged的方法

//当页码改变的时候,加载新一页的数据
    pageChanged=(page)=>{
        //由于我们手动使用BOM对象 实现了跳转 这样不好 最好使用路由的方法
        //实现编程式导航 
        //使用react-router.dom实现编程是导航
        // window.location.href='/#/movie/'+this.state.movieType+'/'+page
        this.props.history.push('/movie/'+this.state.movieType+'/'+page)
    }

在这里插入图片描述

9 点击列表项跳转至电影详情页

创建movieDetail.jsx组件

导入组件
MovieContainer.jsx

import MovieDetail from './sub/MovieDetail.jsx'

在路由中添加switch

//导入路由相关的组件
//Switch:只能匹配到一个路由
import {Link,Route,Switch} from 'react-router-dom'

设置路由匹配规则

 {/*为了防止访问电影详情页的链接(/movies/detail/2159989/)会匹配到以下两个路由
               所以启用exact精确匹配 但是精确匹配也会从往下把所有的路由规则匹配一遍  
               用Switch包裹 如果已经匹配了前面的路由了 那么就不会匹配后面的路由了*/}
               <Switch>
                     {/* 配置详情页路由规则 */}
                     <Route exact path="/movie/detail/:id" component={MovieDetail}></Route>

                    <Route exact path="/movie/:type/:page" component={MovieList}></Route>           
               </Switch>

在将父组件的hietory对象传递给子组件
MovieList.jsx

 {this.state.movies.map((item,i)=>{
                        // 将该父组件的history对象传递给子组件
                        return<MovieItem {...item} key={i} history={this.props.history}></MovieItem>
                    })}

实现点击跳转到子组件
MovieItem

render(){
        return<div className={style.box} onClick={this.goDetail}>
            <img src={this.props.images.small.replace('.jpg','.webp')} className={style.img}></img>
            <h4>电影名称:{this.props.title}</h4>
            <h4>上映年份:{this.props.year}</h4>
            <h4>电影类型:{this.props.genres.join(',')}</h4>
            {/* 使用antd的评分控件 */}
            <Rate disabled defaultValue={this.props.rating.average/2} />
        </div>
    }
    goDetail=()=>{
        this.props.history.push('/movie/detail/'+this.props.id)
    }

在这里插入图片描述

10 实现电影详情页以及返回功能

实现返回功能
导入按钮控件

import { Button } from 'antd';
import { LeftOutlined } from '@ant-design/icons';

 this.state={
            size: 'small'
           
        }
 render(){
        return<div>
             <Button type="primary" 
             shape="round" 
             icon={<LeftOutlined/>} 
             size={this.state.size}
             onClick={this.goBack}>
                 
                返回电影列表页面
             </Button>
          
        </div>

定义点击按钮返回的方法

goBack=()=>{
        this.props.history.go(-1)
    }

导入加载中控件

import { Spin, Alert } from 'antd';
this.state={
            size: 'small',
            //电影信息对象
            info:{},
            isloading:true
        }

注意:不要直接在render函数内部直接渲染 可能会出现数据未及时返回而报错通过调用该方法来渲染 只有当数据获取过来以后 在将数据return

componentWillMount(){
        fetch('https://douban.uieee.com/v2/movie/subject/'+
        this.props.match.params.id)
        .then(response=>{
            return response.json()
        })
        .then(data=>{
            console.log('https://douban.uieee.com/v2/movie/subject/'+
            this.props.match.params.id)
            this.setState({
                info:data,
                //当数据获取回来以后将isloading改为false
                isloading:false
            })
        })
    }
  renderInfo(){
        if(this.state.isloading){
            return<Spin tip="Loading...">
                <Alert
                message="正在请求电影列表"
                description="精彩内容,马上呈现..."
                type="info"
                />
           </Spin>
           
        }else{
            console.log(this.state)
            return<div style={{textAlign:"center"}}>
                
                 <h1>{this.state.info.title}</h1> 
                <img src={this.state.info.images.large}></img>
                <p style={{textIndent:'2em',lineHeight:"30px"}}>{this.state.info.summary}</p>
            </div>
        }
    }

在render中调用

  render(){
        return<div>
             <Button type="primary" 
             shape="round" 
             icon={<LeftOutlined/>} 
             size={this.state.size}
             onClick={this.goBack}>
                 
                返回电影列表页面
             </Button>
             {this.renderInfo()}
        </div>
    }

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值