【问题标题】:Function gets called multiple times in react函数在反应中被多次调用
【发布时间】:2020-05-01 19:52:20
【问题描述】:

我想知道为什么函数在调度时被多次调用。 另外,有没有更好的办法呢,

getData = (value) =>{
  const body = {
    value: value,
    cn: "TH"
  }
return body;
}

renderData(){
  console.log("starts");
  this.props.dispatch(queryData(this.getData(10)));// called repeatedly 
}

render(){
  return(
   <div>{this.renderData()}</div>
  ) 
}

我已经更新了相同类型的不同场景,我想知道有没有其他更好的方法。

场景 2

getData = () =>{
  const body = {
    value: value,
    cn: "TH"
  }
return body;
}
componentDidMount=()=>{
  this.props.dispatch(queryData(this.getData()))
}
componentDidUpdate = () => {
const {allstate} = this.props.querydata 
  if(this.props.querydata){
    this.renderState(allstate);
  }
}
renderState = (data) => {
  const getId = data.map(e=>e.id); //will get array of values [2, 3, 4]
  getid.map(e=>
    this.props.dispatch(queryState(e))); //for every id dispatch props, 
  )
}
render(){
  // will gets this by componentDidMount call
  return (
    <div>

   </div>
  )
}

【问题讨论】:

  • 您不应该在渲染方法中修改状态,因为正是这个原因。

标签: javascript reactjs redux react-redux redux-saga


【解决方案1】:

当视图中有渲染时,renderData 函数会被调用,该函数会派发一些动作,这会再次使您的组件重新渲染。 一种解决方案是将this.renderData() 函数移到渲染之外,可能在constructorcomponentDidMount

【讨论】:

  • 您应该记住的主要一点是,决不能直接从渲染函数调用调度操作。
  • @kias 明白,但我已经更新了场景 2,如果有任何想法,请帮忙,
  • @miyavv 如果调用具有调度操作或状态更新,则不会在渲染内部进行任何调用。相反,您可以使用componentDidUpdate 方法,检查this.props.querydata 是否可用并进行renderState 函数调用。
  • @miyavv 我创建了一个与您的问题类似的小样本。看看codesandbox.io/s/reactreduxupdated-y9c4g
【解决方案2】:

render 函数将被调用每次 React 类得到更新。

如果您的操作queryData 是为了获取数据以显示在组件中,请将其放在componentDidMount 中。它只会在 React 组件首次挂载时调用一次。

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多