鍍金池/ 問答/HTML/ react-router 傳遞參數(shù),父組件傳遞參數(shù)到子頁(yè)面,執(zhí)行兩次。

react-router 傳遞參數(shù),父組件傳遞參數(shù)到子頁(yè)面,執(zhí)行兩次。

react-router版本
"react-router": "^3.0.0",
"react": "^15.5.4",

路由配置
<Route path="/imglivedetial/:mid/:type" component={ImageLiveDetial}/>

因?yàn)榈刂窓谥苯虞斎雲(yún)?shù),不會(huì)更新props.parmars,所以都是在componentWillReceiveProps 和 componentDidMount執(zhí)行一個(gè)共同自定義的刷新props函數(shù) refreshProp()

refreshProp()做api請(qǐng)求或刷新狀態(tài)。但是每次都執(zhí)行兩次。

求解

回答
編輯回答
久礙你

總得來說是我自己寫的不嚴(yán)謹(jǐn),算是曲線救國(guó)了,修改componentWillReceiveProps()變成

  componentWillReceiveProps(nextprops){
    let refresh = false;
    Object.keys(nextprops).forEach((value, index) => {
      if(nextprops[value] != this.props[value]){
        refresh = true;
      }
    })
    if(!refresh) return;
    this.refreshProps(nextprops);
  }

先在 componentWillReceiveProps 判定一下nextprops是否變化了,變化了則刷新組件,這個(gè)暫時(shí)解決了多個(gè)(超過兩個(gè))ajax請(qǐng)求的問題,有幾個(gè)prop參數(shù),componentWillReceiveProps 就會(huì)執(zhí)行幾遍。

然后把a(bǔ)jax請(qǐng)求拆分成單獨(dú)的函數(shù),判斷必填ajax參數(shù)是否為空,為空就不執(zhí)行,解決了兩個(gè)ajax請(qǐng)求的問題(請(qǐng)求參數(shù)不嚴(yán)謹(jǐn),為空也發(fā)送請(qǐng)求。)

2018年7月1日 10:05
編輯回答
未命名

這難道不是很明顯嗎?你自己在refreshProp打個(gè)斷點(diǎn),看下堆棧就好了。

以下是我的不基于事實(shí)的猜想:

頁(yè)面掛載的時(shí)候執(zhí)行一次componentDidMount,從而執(zhí)行refreshProp

頁(yè)面更新階段(props改變)執(zhí)行一次componentWillReceiveProps,從而執(zhí)行refreshProp。

如果你想執(zhí)行一次,為什么不把componentWillReceiveProps中的refreshProp刪掉。

2017年9月8日 12:39