美文网首页
fetch-API-react实现tab切换的思路

fetch-API-react实现tab切换的思路

作者: alicemum | 来源:发表于2021-04-22 09:30 被阅读0次

cnode接口

fetchAPI

用Promise实现
官网: http://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html

fetch("https://cnodejs.org/api/v1/topics?tab=good")
            .then(response => response.json())
            .then(json => {
                this.setState({
                    list: json.data
                })
                console.log(json.data[0]);
            })
            .catch(err => console.log('Request Failed', err));

用async和await实现

let url = "https://cnodejs.org/api/v1/topics?tab=good"
        try {
            let response = await fetch(url);
            let json = await response.json();
            this.setState({
                list: json.data
            })
            console.log(json.data[0]);
        } catch (error) {
            console.log('Request Failed', error);
        }

第一种tab切换

需求: 三个标签对应三个不同排版样式的内容
创建三个组件: Book.jsx Phone.jsx Toy.jsx

import React, { Component } from 'react';
import './Tab.css'
import Book from './components/tab/Book'
import Phone from './components/tab/Phone'
import Toy from './components/tab/Toy'


// 需求分析:  三个tab标签对应三块不同排版的内容,标签切换时,下方的组件切换
class Tab extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tabList: [
                {
                    "id": 4,
                    "title": '图书'
                },
                {
                    "id": 8,
                    "title": '玩具'
                },
                {
                    "id": 10,
                    "title": '手机'
                }
            ],
            curIndex: 0,
            title: "图书"
        }
    }
    toggle = (index,title)=>{
        this.setState({
            curIndex: index,
            title
        })
    }
    getList = ()=>{
        let { title } = this.state
        if (title === "图书"){
            return <Book></Book>
        }
        if (title === "玩具"){
            return <Toy></Toy>
        }
        if (title === "手机"){
            return <Phone></Phone>
        }
    }
    render() {
        let {tabList,curIndex} = this.state
        return (
            <div className="tab-box">
                <ul>
                    {
                        tabList.map((item, index) => {
                            return (
                                <li 
                                    key={item.id} 
                                    onClick={()=>{this.toggle(index,item.title)}}
                                    className={curIndex === index ? 'active': ''}
                                > {item.title}</li>
                            )
                        })
                    }
                </ul>
                {this.getList()}
            </div>
        );

    }
}
export default Tab;

第二种tab切换

需求: 三个标签对应一个内容区,请求不同,数据不同
用浏览器原生API fetch实现

import React, { Component } from 'react';
import "./Tab.css"
class Tab2 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tabList: [
                {
                    "type": "good",
                    "title": "精华"
                },
                {
                    "type": "share",
                    "title": "分享"
                },
                {
                    "type": "ask",
                    "title": "问答"
                }
            ],
            curIndex: 0,
            list: [],
            loading: true
        }
    }
    async getData(type) {
        let url = `https://cnodejs.org/api/v1/topics?tab=${type}`
        try {
            let response = await fetch(url);
            let json = await response.json();
            this.setState({
                list: json.data,
                loading: false
            })
        } catch (error) {
            console.log('Request Failed', error);
        }
    }
    componentDidMount() {
        this.getData('good')
    }

    //切换标签
    toggle(index) {
        this.setState({
            curIndex: index,
            loading: true
        })
        let type = this.state.tabList[index].type
        this.getData(type)
    }
    render() {
        let { tabList, curIndex, list } = this.state
        return (
            <div className="tab-box">
                <ul className="title">
                    {
                        tabList.map((item, index) => {
                            return (
                                <li
                                    key={index}
                                    className={curIndex === index ? "active" : ''}
                                    onClick={() => { this.toggle(index) }}
                                >{item.title}</li>
                            )
                        })
                    }
                </ul>
                <div>
                    {
                        this.state.loading
                            ?
                            <div>loading......</div>
                            :
                            (
                                <ul>
                                    {
                                        list.map((item, index) => {
                                            return (
                                                <li
                                                    key={index}
                                                >{item.title}</li>
                                            )
                                        })
                                    }
                                </ul>
                            )
                    }

                </div>
            </div>
        );
    }
}

export default Tab2;

相关文章

网友评论

      本文标题:fetch-API-react实现tab切换的思路

      本文链接:https://www.haomeiwen.com/subject/onrxrltx.html