函数在反应中被多次调用

miy*_*avv 4 javascript reactjs redux redux-saga react-redux

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

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>
  ) 
}

Run Code Online (Sandbox Code Playgroud)

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

场景二

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>
  )
}
Run Code Online (Sandbox Code Playgroud)

Kai*_*ais 5

当 view 中有 render 时,renderData调用函数来调度一些动作,这再次使您的组件重新渲染。一种解决方案可以将您的this.renderData()功能移到渲染之外,可能在 constructor componentDidMount