多次调用组件:范围错误

时间:2017-04-06 06:15:31

标签: javascript html reactjs

我有这个上传组件。当我运行它时,它打印多行,最后显示错误为

Uncaught RangeError: Maximum call stack size exceeded

似乎多次调用class Upload extends React.Component { constructor(props) { super(props); this.state = { isUpload: false }; this.afterUpload = this.afterUpload.bind(this); this.beforeUpload = this.beforeUpload.bind(this); } beforeUpload(props) { this.setState({isUpload: true}); return ( <div> <h2>Before Upload</h2> </div> ) } afterUpload(props) { this.setState({isUpload: false}); return ( <div> <h1>After upload</h1> </div> ) } render() { const isUpload = this.state.isUpload; console.log("state..." + isUpload); if(isUpload) return this.afterUpload(); return this.beforeUpload(); } } beforeUpload。我无法在此处找到任何错误。

1 个答案:

答案 0 :(得分:1)

你的做法是错误的。您在this.afterUpload();内呼叫render()this.afterUpload()调用setState()进而调用render()方法,这将导致另一次调用this.afterUpload();因此循环。记住你调用setState()方法的evrytime,你的组件会被重新渲染。

检查:

  1. 呈现的组件。在render()方法中,this.beforeUpload()被调用。

  2. 在beforeUpload中,this.setState({isUpload: true});将再次调用render方法,这次调用this.afterUpload()

  3. this.afterUpload()this.setState({isUpload: false}),将再次调用render(),这次this.beforeUpload()将被调用。

  4. 上面的步骤重复..因此循环。

  5. 推荐的approcah。

    componentWillMount(){
       this.beforeUpload()
    } 
    
    
    beforeUpload(props) {
      this.setState({isUpload: true},()=>{//Put return statement inside setState callback
         return (
        <div>
          <h2>Before Upload</h2>
        </div>
      )
     });
    
    
    }