如何在react和redux中的componentDidUpdate()中调用action和设置state(防止中篇循环



我的项目中有一个导航栏,它对所有人来说都是通用的并且它有一个输入文本字段

<input
placeholder="Search Assets"
type="text"
id="searchTerm"
onChange={this.searchAsset}
value={this.state.searchValue}
/>

和函数onChange我正在重定向到库页面

searchAsset = event => {
const searchValue = event.target.value;
this.setState({ searchValue });
if (searchValue.trim().length > 2) {
this.props.history.push(`/company/library?q=${searchValue}`);
}
};

在库页面中,我调用componentDidMount((中的搜索操作

componentDidMount() {
const params = new URLSearchParams(this.props.location.search);
const q = params.get('q');
this.setState({ searchValue: q });
this.props.actions.searchAssets({ page: 0, searchString: q });
}

现在的问题是每当我再次搜索时——假设最初我搜索了";图像";在得到结果后,我删除了顶部导航中的文本,并再次搜索文本";下载";我没有从后端得到任何响应

现在我想用来解决这个问题

componentDidUpdate(prevProp, prevState) {
const params = new URLSearchParams(this.props.location.search);
const q = params.get('q');
if (q !== prevState.searchValue) {
this.props.actions.searchAssets({ page: 0, searchString: q });
}
}

并且我得到错误超过了最大更新深度。当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生这种情况

问题

您的componentDidUpdate版本与componentDidMount版本不完全匹配。您总是比较qprevState.searchValue,但不更新状态,因此在下一次更新时比较为false。q !== prevState.searchValue永远不会导致false,并且您似乎将导致渲染循环的一系列操作排入队列。

解决方案

缓存当前搜索结果以进行下一次状态更新比较,因此只有当搜索查询到达时才会运行效果。

componentDidUpdate(prevProp, prevState) {
const params = new URLSearchParams(this.props.location.search);
const q = params.get('q');
if (q !== prevState.searchValue) {
this.setState({ searchValue: q }); // <-- update state with search value
this.props.actions.searchAssets({ page: 0, searchString: q });
}
}

最新更新