我在使用导航离开此组件时遇到问题我得到此错误:warning.js:36警告:setState(...):"只能更新已安装或安装组件。这通常意味着您在已卸载的组件上调用了setState()。这是一个无操作。请检查ProjectsHeader组件的代码。"
现在,我已经查看了componentWillUnmount的文档,这些文档指出"在从DOM卸载组件之前立即调用。
在此方法中执行任何必要的清理,例如使计时器无效或清除在componentDidMount中创建的任何DOM元素。"
问题是我不知道该怎么做。我已经查看了其他Stack溢出示例,但我不了解它们并且无法弄明白。对我来说,似乎不是一个足够好的例子来理解如何做到这一点。我理解生命周期,我不知道如何执行它。
这是我的代码:
import React from 'react';
import jQuery from 'jquery';
import $ from 'jquery';
import ProjectsHeaderLinks from "./ProjectsHeaderLinks.jsx";
export default class ProjectsHeader extends React.Component {
constructor() {
super()
this.state = {
class: "not-sticky-div",
class2: "hidden-span",
class3: "false"
}
}
componentDidMount() {
this.scrollTop();
}
componentWillUnmount(){
this.scrollTop = null;
console.log("unmounted");
}
scrollTop(){
var that = this;
let head = $(".header");
let stick = "sticky";
let projHead = document.getElementById("projHead");
$(window).scroll(function() {
$(window).scrollTop() > 400
? head.addClass(stick)
: head.removeClass(stick);
let newValue = projHead.classList.value.split(' ', 2);
for (var i = 0; i < newValue.length; i++) {
newValue[i] === "sticky"
? that.setState({class: "sticky-div", class2: "visible-span", class3: "true"})
: that.setState({class: "not-sticky-div", class2: "hidden-span", class3: "true"});
}
})
}
render() {
return (
<div id="projHead" className="header">
<div className={this.state.class}>
{this.state.class === "not-sticky-div"
? <div>"This is My Projects Page" --Lonnie McGill</div>
: <div> <ProjectsHeaderLinks/> </div>
}
</div>
</div>
)
}
}
答案 0 :(得分:1)
解决问题:
componentWillUnmount(){
$(window).unbind("scroll");
}