函数在反应中被多次调用
Function gets called multiple times in react
我想知道为什么该函数在调度时被多次调用。
还有,有什么更好的办法吗,
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>
)
}
render
函数将被调用 每次 React class 得到更新。
如果您的操作 queryData
是为了获取数据以在组件中显示,请将其放在 componentDidMount
中。它只会在 React 组件首次挂载时被调用一次。
当视图中有渲染时,renderData
函数被调用以分派一些动作,这再次使您的组件重新渲染。
一种解决方案是将 this.renderData()
函数移出 render ,可能在 constructor
或 componentDidMount
中
我想知道为什么该函数在调度时被多次调用。 还有,有什么更好的办法吗,
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>
)
}
render
函数将被调用 每次 React class 得到更新。
如果您的操作 queryData
是为了获取数据以在组件中显示,请将其放在 componentDidMount
中。它只会在 React 组件首次挂载时被调用一次。
当视图中有渲染时,renderData
函数被调用以分派一些动作,这再次使您的组件重新渲染。
一种解决方案是将 this.renderData()
函数移出 render ,可能在 constructor
或 componentDidMount