简体   繁体   English

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

[英]Redux/React-Router - Being Able to Send URL's with Parameters with Client Side Routing

I'm looking to be able to have Redux populate state correctly when given a search parameter url. 我希望能够在给定搜索参数URL的情况下使Redux正确填充状态。

Currently my flow goes as follows: 目前,我的流程如下:

Search -> 搜索->

<Redirect to={{
  pathname: '/search',
  search: `?item-name=${this.props.searchQuery}`
}} />

Which then redirects it to a /search component = {SearchResults} 然后将其重定向到/search component = {SearchResults}

In SearchResults, it is able to get items which were queried from the server due to a Redux action dispatching a GET Request. 在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));
});

And therefore that object is available in Search Results by the Redux state since I've connected it. 因此,自连接以来,该对象在Redux状态的“搜索结果”中可用。

function mapStateToProps(state) {
   return {
   // Gets the list of fetched items
   items: state.items.items
 };
}

If I were to give a friend https://mywebsite.com/search?item-name=foo my "items" state would be empty because it did not go through all the actions being dispatched, and therefore technically did not grab the information from my db. 如果我要给一个朋友https://mywebsite.com/search?item-name=foo我的“项目”状态将为空,因为它没有执行所有分派的操作,因此从技术上讲不会获取该信息从我的数据库。

Is there anyway I can allow this item information to be requested on entering the above url while still keeping Redux/Routing stuff done client-side? 无论如何,我是否可以允许在输入上述网址时请求此项目信息,同时仍将Redux / Routing内容保留在客户端?

This is similar to saying that when you refresh the page https://mywebsite.com/search?item-name=foo your axios call doesn't get fired. 这类似于说您刷新页面https://mywebsite.com/search?item-name=foo您的axios调用不会被触发。

What you'll need to do is create something like this: 您需要做的是创建如下内容:

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
}

That should trigger the request if the page is refreshed or someone navigates directly to it. 如果页面刷新或有人直接导航到该页面,则应该触发该请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM