javascript - Redux/React-Router - 能够通过客户端路由发送带有参数的 URL

标签 javascript reactjs express redux react-router

我希望在给定搜索参数 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/

相关文章:

javascript - webpack [hash] 和 [chunkhash] 的用途是什么?

javascript - 在Vue.JS方法中传递的字符串trim()不起作用

javascript - 为什么在尝试锁定或解锁 Excel API 中的一系列单元格时出现 AccessDenied

javascript - 当聚焦位于模式内部的输入时防止页面滚动

javascript - ReactDom 没有用 react 和 webpack 定义

javascript - 组件无法正确更新 View

javascript - 服务器终止时保存文件

javascript - 在客户端存储 mySQL 查询结果以供将来的请求使用

javascript - 向路由添加其他信息 - TypeScript 的解决方法?

node.js - Passport.js - 将 {user : req. user} 隐式传递给模板?