React:带参数调用函数会导致无限循环 [英] React: Invoking function with parameters causes infinite loop
问题描述
所以,我有一个组件,它使用像这样的道具呈现另一个组件:
`<Component_Two onChange={this.changeSomething}/></Component_One>`
在 Component_One 中,函数 changeSomething()
接受一个参数:id
所以在 Component_One
中,changeSomething()
看起来像这样:
`changeSomething(id) {this.setState({something: id});}`
Component_Two
看起来像这样:
`<div onClick={this.props.onChange(0)}><div className="徽章"></div><div onClick={this.props.onChange(1)}><div className="徽章"></div>
<div onClick={this.props.onChange(2)}><div className="徽章"></div>
`
对象是让 Component_One
中的 this.state.something
等于 Component_Two 中 div 的显式类型
id
...
但它会抛出此错误:SCRIPT5022:超出最大更新深度.当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,就会发生这种情况.React 限制嵌套更新的数量以防止无限循环.
那么如何在不创建无限循环的情况下将显式类型的参数传递给prop 函数"?
您应该将一个函数传递给 onClick
处理程序,但您正在调用该函数.因此,该函数会被立即调用并设置导致重新渲染的 state
,从而导致无限循环.传递一个函数而不是
onClick={() =>this.props.onChange(0)}
So, I have a component that renders another component with a prop like so:
`<Component_One>
<Component_Two onChange={this.changeSomething} />
</Component_One>`
Inside Component_One, the function changeSomething()
takes one parameter: id
So inside Component_One
, changeSomething()
looks like this:
`changeSomething(id) {
this.setState({something: id});
}`
Component_Two
looks like this:
`<div id="componenttwo">
<div onClick={this.props.onChange(0)}>
<div className="badge"></div>
</div>
<div onClick={this.props.onChange(1)}>
<div className="badge"></div>
</div>
<div onClick={this.props.onChange(2)}>
<div className="badge"></div>
</div>
</div>`
The object is to get this.state.something
inside Component_One
to equal the explicitly typed id
of the div in Component_Two
...
but instead it throws this error: SCRIPT5022: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
So how do I pass an explicitly typed argument to a "prop function" without creating an infinite loop?
You should pass a function to onClick
handler but you are calling the function. Because of that the function is called immediately and set the state
which causes rerender, resulting in infinite loop. Pass a function instead like
onClick={() => this.props.onChange(0)}
这篇关于React:带参数调用函数会导致无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!