[![在此处输入图片描述][1]][1]
这是我项目的顶部导航栏和 [![在此处输入图片描述][2]][2]
当我点击博客按钮时,所有博客的列表都会呈现出来,在这个组件中,我现在有一个搜索选项,当我有搜索文本时,比如说“vue”,然后我会得到所需的结果
handleSubmit = values => {
const { size } = this.state;
this.setState({ searchString: values.searchString, isSearch: true });
SearchSchema.searchString = this.state.searchString;
this.props.history.push(`/blogs?q=${values.searchString}`);
this.props.actions.loadBlogs({ page: 0, size, searchString: values.searchString });
};
这是博客组件的componentDidMount
componentDidMount = () => {
const { size } = this.state;
const params = new URLSearchParams(this.props.location.search);
const q = params.get('q');
if (q) {
this.setState({ searchString: q, isSearch: true });
this.props.actions.loadBlogs({ page: 0, searchString: q, size });
} else {
this.setState({ searchString: '', isSearch: false });
this.props.actions.loadBlogs({ page: 0, size });
}
};
当我再次点击 Top Navbar 中的博客(在屏幕截图中)获得结果后,url 已更改但未获取所有博客
<Link className="nav-link" to="/blogs">
Blogs
</Link>
带有搜索结果和 url 的屏幕截图将是 http://localhost:8075/blogs?q=vue 当我再次单击博客按钮时,相同的屏幕截图也适用 url 正在更改但博客未更新 http://localhost:8075/blogs
我解决了这个问题
componentDidUpdate(prevProp, prevState) {
const { size } = this.state;
const params = new URLSearchParams(this.props.location.search);
const q = params.get('q');
if (q !== prevState.searchString) {
console.log('-------- in if -----------');
this.setState({ searchString: q });
this.props.actions.loadBlogs({ page: 0, size });
}
}
但不确定这是否正确 并且通过使用它,我仍然在搜索输入字段中获得先前的值
答案 0 :(得分:1)
这可以在 componentDidUpdate
的帮助下完成,您可以比较 params
中的搜索 componentDidUpdate
,并且可以在它们不同时执行您的更改。
componentDidUpdate(prevProps) {
if(prevProps.location.search !== this.props.location.search) {
this.init();
}
}
componentDidMount {
this.init();
};
init = () => {
const { size } = this.state;
const params = new URLSearchParams(this.props.location.search);
const q = params.get('q');
if (q) {
this.setState({ searchString: q, isSearch: true });
this.props.actions.loadBlogs({ page: 0, searchString: q, size });
} else {
this.setState({ searchString: '', isSearch: false });
this.props.actions.loadBlogs({ page: 0, size });
}
}