我希望在给定搜索参数 url 时能够让 Redux 正确填充状态。
目前我的流程如下:
搜索 ->
<Redirect to={{
pathname: '/search',
search: `?item-name=${this.props.searchQuery}`
}} />
然后将其重定向到 /search 组件 = {SearchResults}
在 SearchResults 中,它能够获取由于 Redux 操作调度 GET 请求而从服务器查询的项目。
return axios.get(`/api/search?item-name=${itemName}`)
.then(response => {
let json = response.data;
dispatch(requestItemsSuccess(json));
}).catch(error => {
dispatch(requestItemsFailure(itemName));
});
因此,自从我连接该对象以来,该对象在 Redux 状态的搜索结果中可用。
function mapStateToProps(state) {
return {
// Gets the list of fetched items
items: state.items.items
};
}
如果我要给 friend https://mywebsite.com/search?item-name=foo
,我的“items”状态将为空,因为它没有经历所有的操作已调度,因此从技术上讲并没有从我的数据库中获取信息。
无论如何,我是否可以允许在输入上述网址时请求此项目信息,同时仍然保持 Redux/Routing 内容在客户端完成?
最佳答案
这类似于当您刷新页面时 https://mywebsite.com/search?item-name=foo
您的 axios 调用不会被触发。
您需要做的是创建如下内容:
componentDidMount() {
const {items} = this.props; // assuming you can check whether items is populated
if (!items) {
this.props.dispatch(
makeSearchResultsAxiosCall(this.props.location.query.item-name)
)
}
// use this.props.location.query to access the query parameter
}
如果页面刷新或有人直接导航到该页面,应该会触发请求。
关于javascript - Redux/React-Router - 能够通过客户端路由发送带有参数的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46271243/