我正在nextjs中工作并覆盖_app.js以便在所有页面中显示标题。我已将标题放置在布局中,并在_app.js中使用它。在标题中有搜索栏。在搜索时,搜索结果必须为从标头发送到其他组件。Api工作正常,但在警告以下返回
无法在已卸载的组件上执行React状态更新。这是 无操作,但表示您的应用程序内存泄漏。修理, 取消所有订阅和异步任务 componentWillUnmount方法。
constant.js
export var searchKey = "";
export const setSearchKey = (value) => {
searchKey = value;
}
export const getSearchKey = (value) => {
return searchKey;
}
header.js
import * as searchConst from '../../static/constants/constants';
class HeaderComponent extends Component {
state = {
authType: true
}
componentDidMount() {
Router.events.on('routeChangeComplete', this.routeChangeHandler);
}
routeChangeHandler(url) {
url === '/appUser' ? this.setState({authType: true}) : this.setState({authType: false})
}
onSearch(event) {
ApiService.onSearchUsers(0, this.state.authType, document.getElementById('search-input').value).then(res => {
console.log(res);
searchConst.setSearchKey(document.getElementById('search-input').value); //if i remove this line then there is no warning
this.props.parentCallBack(userdata);
});
}
render() {
return (
<div className="search-col">
<Input id="search-input" className="text-box" placeholder="Enter name or Email.."
onKeyDown={($event) => this.onSearch($event)}
prefix={<Icon type="search" onClick={() => this.onSearch}></Icon>}></Input>
</div>
)
}
}
答案 0 :(得分:1)
发生此警告是因为要在组件安装上设置状态。如果由于某种原因在状态更新之前已卸载组件,则会收到警告。避免警告的一种方法是在mounted
中将componentWillUnmount
的状态设置为false并在修改状态之前对其进行检查:
state = {
authType: true,
mounted: true
}
componentDidMount() {
Router.events.on('routeChangeComplete', this.routeChangeHandler);
}
componentWillUnmount() {
setState({
mounted: false
});
}
routeChangeHandler(url) {
if (mounted) {
this.setState({
authType: url === '/appUser'
})
}
}