V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
triplecheese

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

  •  
  •   triplecheese · Apr 24, 2019 · 3929 views
    This topic created in 2572 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
        1
    fengbjhqs  
       Apr 24, 2019
    componentWillMount 17 版以后可能就没有了,
    triplecheese
        3
    triplecheese  
    OP
       Apr 24, 2019
    @fengbjhqs 好像是的,看来还是用 componentDidMount 比较好一点
    triplecheese
        4
    triplecheese  
    OP
       Apr 24, 2019
    @paullee 了解了,谢谢
    Sapp
        5
    Sapp  
       Apr 24, 2019
    componentWillMount 不适合做异步

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