triplecheese

React 的 API 调用放在生命周期的哪个部分最好?

  •  
  •   triplecheese · Apr 24, 2019 · 4464 views
    This topic created in 2757 days ago, the information mentioned may be changed or developed.

    在读的一本叫《 The Road to learn React 》的书里面,API 调用是放在 render 之后的 componentDidMount 里的,但是刚才在油管上看的一个视频里面是放在 render 之前的 componentWillMount 里的,两种方法好像都能完成调用,这只是习惯问题,还是存在孰好孰坏之分?

    13 replies  •  2019-04-24 15:04:38 +08:00
    fengbjhqs
    fengbjhqs
    Apr 24, 2019
    1
    componentWillMount 17 版以后可能就没有了,
    triplecheese
    triplecheese
    OP
    Apr 24, 2019
    3
    @fengbjhqs 好像是的,看来还是用 componentDidMount 比较好一点
    triplecheese
    triplecheese
    OP
    Apr 24, 2019
    4
    @paullee 了解了,谢谢
    Sapp
    Sapp
    Apr 24, 2019
    5
    componentWillMount 不适合做异步

    不过现在不都是 hooks 了吗?
    triplecheese
    triplecheese
    OP
    Apr 24, 2019
    6
    @Sapp 还没学到 Hooks🤣
    Sapp
    Sapp
    Apr 24, 2019
    7
    @triplecheese 如果不是为了面试,其实那些 api 不学也行了...
    ChefIsAwesome
    ChefIsAwesome
    Apr 24, 2019
    8
    你把 willmount 当作 constructor 就行了。
    triplecheese
    triplecheese
    OP
    Apr 24, 2019
    9
    @ChefIsAwesome 嗯嗯,有道理
    zqx
    zqx
    Apr 24, 2019 via Android
    10
    构造函数和 didmount 的执行时间可能也就差几微秒,这两个都可以吧?
    duzhihao
    duzhihao
    Apr 24, 2019 via iPhone
    11
    我记得官方文档建议放在 componentDidMount 里面
    CocaColf
    CocaColf
    Apr 24, 2019
    12
    componentDidMount 里面
    MichaelJack
    MichaelJack
    Apr 24, 2019
    13
    componentWillMount 已弃用 现在只能在 componentDidMount
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1478 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 16:39 · PVG 00:39 · LAX 08:39 · JFK 11:39
    ♥ Do have faith in what you're doing.