当使用不同的搜索参数推送相同的URL时,如何让组件重新呈现?React Redux React路由器



我正在使用React Redux和React Router构建一个web应用程序。在我的应用程序中,我有一个名为Listings的组件,用户可以在其中使用搜索栏来筛选某些类型的列表。只要用户不在列表页面上,一切都可以完美运行。但是,当用户尝试从列表页面而不是主页使用搜索栏时,该组件不会重新呈现。我有点明白为什么会发生这种情况,因为DOM没有改变,但还没有找到解决方法。

我也得到了这样的警告";react_devtools_backend.js:4026警告:哈希历史不能推送相同的路径;新的条目将不会被添加到历史堆栈";

以下是搜索组件中的相关代码

handleSubmit(e) {
e.preventDefault;
const searchUrl = new URLSearchParams(this.state).toString();
this.props.history.push({
pathname: `/listings/`,
key: Math.random(),
search: `${searchUrl}`
})
}

下面是我的Listings组件中的一些代码

class Listings extends React.Component {
constructor(props) {
super(props);
this.state = {listings: props.listings};
}
componentDidMount() {
this.props.indexListings();
}
componentDidUpdate(prevProps) {
if (this.props.listings != prevProps.listings) {
if (this.props.history.location.search) {
const queryString = require('query-string');
const parsed = queryString.parse(this.props.location.search);
const listings = [...this.props.listings];
this.setState({listings: listings.filter(listing => listing.city.includes(parsed.city))});
} else {
const listings = [...this.props.listings];
this.setState({listings: listings});
}
}
}

列出集装箱代码

import { connect } from "react-redux";
import { indexListings } from "../../actions/listing_actions";
import Listings from "./Listings";
const mapStateToProps = state => ({
listings: Object.values(state.entities.listings)
})
const mapDispatchToProps = dispatch => ({
// this gets all the listings from the backend
indexListings: () => dispatch(indexListings())
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(Listings);

以及我的应用程序组件中的代码

const App = () => (
<Switch>
<AuthRoute path="/login" component={LoginFormContainer} />
<AuthRoute path="/signup" component={SignupFormContainer} />
<Route path = "/listings/" component={ListingsContainer}/>
<Route path = "/users/show/" component={UserContainer}/>
<Route path = "/listing/new/" exact component={NewListingContainer}/>
<Route path = "/listing/:id/" component={ShowListingContainer}/>        
<Route path = "/" component={Splash} />
</Switch>
);

任何建议或建设性的反馈都将不胜感激!

@Drew-Reese认为我的ComponentDidUpdate逻辑有缺陷是正确的,现在问题已经解决。我认为问题是第二次调用组件中的任何方法,但我错了。第二次使用搜索栏时(已经在Listings组件中(,componentDidUpdate确实被调用了,但我的条件没有在props.histroy中注册更改。此后,我在componentDidUpdate顶部将if (this.props.listings != prevProps.listings)更改为if (this.props != prevProps)!感谢大家帮我解决这个问题。

最新更新