函数在反应中被多次调用

问题描述 投票:1回答:2

我想知道为什么函数在多次调度时会被多次调用。另外,还有什么更好的方法可以做,

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
2个回答
2
投票

[当视图中存在渲染时,将调用renderData函数,该函数将分派一些操作,这又使您的组件重新渲染。一种解决方案是将this.renderData()函数移至渲染器之外,可能位于constructorcomponentDidMount


0
投票

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

如果您的操作queryData用于获取要在组件中显示的数据,请将其放在componentDidMount中。首次安装React组件时,它将仅被调用一次。

© www.soinside.com 2019 - 2024. All rights reserved.