component和render在react router中的應用

在react router項目中,有這樣的一個需求髓梅,首先展示用戶名列表辜御,點擊某個用戶名后阁谆,根據(jù)用戶名在后臺取得用戶具體信息在詳情頁進行展示。

此時可以將詳情頁封裝成一個組件璧尸,利用react router將userId傳遞給詳情頁組件澎粟,詳情頁組件向后臺請求數(shù)據(jù),然后進行展示重贺。

component

使用component時,詳情頁組件代碼如下

import {PureComponent, Component} from "react";
import React from "react";

class ComponentUser extends PureComponent {

    constructor(props) {
        super(props);
        this.state = {}
    }

    getUserId = () => {
        const {
            match: {
                params: {id},
            },
        } = this.props;
        return id;
    };

    fetchContent = (userId) => {
        console.log("fetch");
        this.setState({content: "loading"});
        new Promise(resolve => {
            setTimeout(() => {
                resolve("content of " + userId)
            }, 2000)
        }).then(content => {
            this.setState({content})
        })
    };

    componentDidMount() {
        const userId = this.getUserId();
        this.fetchContent(userId);
    }

    render() {
        const userId = this.getUserId();
        const {content} = this.state;

        return (
            <div>
                <div>{userId}</div>
                <div>{content}</div>
            </div>

        )
    }
}

export default ComponentUser

列表頁代碼如下

import React from "react";
import {BrowserRouter as Router, Route, Link} from "react-router-dom";
import RenderUser from './RenderUser'
import ComponentUser from './ComponentUser'

const App = () => (
    <Router>
        <div>
            <nav>
                <ul>
                    <li>
                        <Link to="/componentUser/user1">userA</Link>
                    </li>
                    <li>
                        <Link to="/componentUser/user2">userB</Link>
                    </li>
                </ul>
            </nav>

            <Route path="/componentUser/:id" component={ComponentUser}/>
        </div>
    </Router>
);

export default App;

不過此時會有個問題崇堵,切換點擊切換userA和userB的時候,發(fā)現(xiàn)頁面并沒有更新涵紊,這是由component屬性的性質(zhì)決定的驱负,react會進行組件復用。

所以需要在組件中添加componentDidUpdate函數(shù),期望在userId發(fā)生變化后重新獲取數(shù)據(jù)拼缝。

import {PureComponent, Component} from "react";
import React from "react";

class ComponentUser extends PureComponent {

    constructor(props) {
        super(props);
        this.state = {}
    }

    getUserId = () => {
        const {
            match: {
                params: {id},
            },
        } = this.props;
        return id;
    };

    fetchContent = (userId) => {
        console.log("fetch");
        this.setState({content: "loading"});
        new Promise(resolve => {
            setTimeout(() => {
                resolve("content of " + userId)
            }, 2000)
        }).then(content => {
            this.setState({content})
        })
    };

    componentDidMount() {
        const userId = this.getUserId();
        this.fetchContent(userId);
    }

    componentDidUpdate(prevProps) {
        const userId = this.getUserId();
        const {
            match: {
                params: {id: previousUserId},
            },
        } = prevProps;
        if (userId !== previousUserId) {
            this.fetchContent(userId);
        }
    }

    render() {
        const userId = this.getUserId();
        const {content} = this.state;

        return (
            <div>
                <div>{userId}</div>
                <div>{content}</div>
            </div>

        )
    }
}

export default ComponentUser

這里要注意的是瘟檩,componentDidUpdate中需要判斷當前的userId是否和原來的userId一致,只有不一致的時候才需要重新獲取數(shù)據(jù)奏赘。不這樣做的話梁只,會導致無限循環(huán)的setState和componentDidUpdate。

render

使用render則可以減少三分之一的代碼行數(shù)翰绊,此時詳情頁組件代碼如下

import {PureComponent} from "react";
import React from "react";

class RenderUser extends PureComponent {

    constructor() {
        super();
        this.state = {}
    }

    componentDidMount() {
        console.log("fetch");
        this.setState({content: "loading"});
        const {userId} = this.props;
        new Promise(resolve => {
            setTimeout(() => {
                resolve("content of " + userId)
            }, 1000)
        }).then(content => {
            this.setState({content})
        })
    }


    render() {
        const {userId} = this.props;
        const {content} = this.state;

        return (
            <div>
                <div>{userId}</div>
                <div>{content}</div>
            </div>

        )
    }
}

export default RenderUser

列表頁代碼如下

import React from "react";
import {BrowserRouter as Router, Route, Link} from "react-router-dom";
import RenderUser from './RenderUser'
import ComponentUser from './ComponentUser'

const App = () => (
    <Router>
        <div>
            <nav>
                <ul>
                    <li>
                        <Link to="/renderUser/user1">user1</Link>
                    </li>
                    <li>
                        <Link to="/renderUser/user2">user2</Link>
                    </li>
                </ul>
            </nav>

            <Route path="/renderUser/:id" render={
                ({match}) => (<RenderUser key={match.params.id} userId={match.params.id}/>)
            }/>
        </div>
    </Router>
);

export default App;

可以看到由于將userId作為組件的key溃肪,可以避免組件復用,從而降低代碼的復雜程度。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子励翼,更是在濱河造成了極大的恐慌伯病,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件木缝,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機厘托,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門考杉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來丸卷,“玉大人萎坷,你說我怎么就攤上這事住闯。” “怎么了雇寇?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵出革,是天一觀的道長。 經(jīng)常有香客問我,道長皂贩,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任挤聘,我火速辦了婚禮沟饥,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己购桑,他們只是感情好缭贡,可當我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布莹汤。 她就那樣靜靜地躺著抹竹,像睡著了一般沽翔。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天堤舒,我揣著相機與錄音某残,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播魏保,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼胯舷,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤昙啄,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡烹植,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖顶岸,靈堂內(nèi)的尸體忽然破棺而出卷谈,到底是詐尸還是另有隱情朗兵,我是刑警寧澤,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響心铃,放射性物質(zhì)發(fā)生泄漏愉棱。R本人自食惡果不足惜朋其,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一簇爆、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦粱栖、人聲如沸渣淤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽呀页。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間谍咆,已是汗流浹背港粱。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓帽驯,卻偏偏與公主長得像,于是被迫代替她去往敵國和親尼变。 傳聞我的和親對象是個殘疾皇子蛉威,可洞房花燭夜當晚...
    茶點故事閱讀 45,060評論 2 355