简体   繁体   English

函数在反应中被多次调用

[英]Function gets called multiple times in react

I would like to know why the function gets called multiple times wheh dispatch.我想知道为什么在调度时多次调用该函数。 Also, is there any better way to do,还有,有没有更好的办法,

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

I have updated the different scenario by same type, I need to know is there any other better way to.我已经更新了相同类型的不同场景,我需要知道有没有其他更好的方法。

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

When there is render in view , renderData function gets called which dispatch some action, and again this make your component re-render.当视图中有渲染时,会调用renderData函数来调度一些动作,这再次使您的组件重新渲染。 One solution can be move your this.renderData() function outside the render , may be in constructor or componentDidMount一种解决方案可以将您的this.renderData()函数移到 render 之外,可能在constructorcomponentDidMount

render function will be called every time React class get updated.每次更新 React 类都会调用render函数。

If your action queryData is for fetching data to display in component, put it inside componentDidMount .如果您的操作queryData用于获取要在组件中显示的数据,请将其放在componentDidMount It will only be called once when React component first mounted.它只会在 React 组件第一次挂载时被调用一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM