Javascript 函数在react中被多次调用
我想知道为什么函数在分派时被多次调用。 还有,有没有更好的办法Javascript 函数在react中被多次调用,javascript,reactjs,redux,react-redux,redux-saga,Javascript,Reactjs,Redux,React Redux,Redux Saga,我想知道为什么函数在分派时被多次调用。 还有,有没有更好的办法 getData = (value) =>{ const body = { value: value, cn: "TH" } return body; } renderData(){ console.log("starts"); this.props.dispatch(queryData(this.getData(10)));// called repeatedly } render(){
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>
)
}
getData=(值)=>{
常数体={
价值:价值,
cn:“TH”
}
返回体;
}
renderData(){
控制台日志(“启动”);
this.props.dispatch(queryData(this.getData(10));//重复调用
}
render(){
返回(
{this.renderData()}
)
}
我已经用相同的类型更新了不同的场景,我需要知道是否还有其他更好的方法
情景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>
)
}
getData=()=>{
常数体={
价值:价值,
cn:“TH”
}
返回体;
}
componentDidMount=()=>{
this.props.dispatch(queryData(this.getData()))
}
componentDidUpdate=()=>{
const{allstate}=this.props.querydata
if(this.props.querydata){
此.renderState(所有状态);
}
}
renderState=(数据)=>{
const getId=data.map(e=>e.id);//将获取值数组[2,3,4]
getid.map(e=>
this.props.dispatch(queryState(e));//对于每个id dispatch props,
)
}
render(){
//将通过componentDidMount调用获取此信息
返回(
)
}
render
函数将在每次更新反应类时调用
如果您的操作
queryData
用于获取要在组件中显示的数据,请将其放入componentDidMount
中。当React组件第一次装入时,它将只被调用一次。当视图中有render时,renderData
函数将被调用,该函数将分派一些操作,这将再次使组件重新呈现。
一种解决方案是将您的
this.renderData()
函数移到渲染外部,可能在构造函数中或componentDidMount中,您不应该修改渲染方法中的状态,因为正是这个原因。@kia感谢您的回复,如果我在componentDidMount
中这样做的话,在渲染之前,可以通过将arg作为函数传递给函数来立即访问这些道具。您应该记住的主要一点是,决不能直接从渲染函数调用分派操作。@Kia是的,了解,但我已经更新了场景2,如果您有任何想法,@miyavv不会在render内部进行任何调用,如果该调用具有分派操作或状态更新。相反,您可以使用componentdiddupdate
方法,检查this.props.querydata
是否可用,并进行renderState
函数调用。@miyavv我创建了一个类似于您的问题的小示例。看一看