繁体   English   中英

componentDidUpdate - 错误:超出最大更新深度

[英]componentDidUpdate - Error: Maximum update depth exceeded

class Suggestions extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false
        }

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(event) {
        console.log(event.target.value)
    }

    componentDidUpdate(props, state) {
        if(props.dataSearchBox) {
            this.setState({visible: true})

        } else {
            this.setState({visible: false})
        }
    }

    render() {
        return (
            <div className={`g${this.state.visible === true ? '': ' h'}`}>
                <ul>
                </ul>
            </div>
        );
    }
}
export default Suggestions;

我试图根据道具更改设置状态,但是我在componentDidUpdate收到以下错误:

There was an error! Error: 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.

我在这儿干什么呢?

你的问题在这里:

componentDidUpdate(props, state) {
    if(props.dataSearchBox) {
        this.setState({visible: true})

    } else {
        this.setState({visible: false})
    }
}

componentDidUpdate被调用,它设置状态,触发componentDidUpdate ... 一轮又一轮。

您是否需要一个单独的状态属性来处理这个问题? 这有点反模式——你已经有了你需要的东西作为道具,只需使用它的值来直接控制可见性:

render() {
    return (
        <div className={`g${this.props.dataSearchBox ? '': ' h'}`}>
            <ul>
            </ul>
        </div>
    );
}

暂无
暂无

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

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