History push не работает use history

React history.push () обновляет URL, но не переходит на него в браузере

К этому моменту я много читал о реакции-маршрутизаторе v4 и библиотеке истории npm, но, похоже, ничего не помогло мне.

Мой код работает должным образом до того момента, когда он должен перемещаться и выполнять простое перенаправление при изменении URL-адреса с помощью метода history.push (). URL-адрес меняется на указанный маршрут, но не выполняет перенаправление на нажатие кнопки. Заранее спасибо, еще учусь прореагировать-роутер .

Я бы хотел, чтобы при нажатии кнопки выполнялось простое перенаправление без , которое затем перезагружает всю страницу.

5 ответов

Убедитесь, что у вас нет вложенных тегов BrowserRouter.

У меня возникла эта проблема наact-router v4, но я решил ее после изменения приложения, чтобы только BrowserRouter находился на самом верхнем уровне, как в примере ниже.

У меня точно такая же проблема.

После некоторых поисков я обнаружил эту проблему с реагирующим маршрутизатором

В настоящее время у меня понижение реакции-маршрутизатора до версии 3, и я использую browserHistory из пакета react-router , и он работает нормально.

Вам не нужно переходить на версию 3, React-Router 4.0.0 полностью способен выполнить то, что требует OP.

Это пользовательский объект истории, поэтому вы должны использовать для синхронизации его с реагирующим маршрутизатором вместо
, как я и предполагал.

Попробуйте это вместо этого:

Как только ваш пользовательский объект истории передается через реквизит истории Router, history.push должен работать так же, как и ожидалось в любом месте вашего приложения. (возможно, вы захотите поместить свой объект истории в файл конфигурации истории и импортировать его в места, где вы хотите программно маршрутизировать).

Для получения дополнительной информации см. объект истории React Router

Рендеринг это обновит при изменении маршрута

Источник

Component is not getting rendered after history.push()

On a button click, I am getting the URL changed by doing history.push()

and hoping the component mentioned in the Route for that URL would render but that is not happening. Though, on refreshing that component is getting rendered as expected. But I don’t get that why it is not rendering as soon as the URL is changing. I’ve tried wrapping the component inside withRouter .

as well as passing history in Router which I think same as using BrowserRouter .

but not getting any luck with this. Can anyone explain why is this happening?
P.S I went through the answers here but they didn’t help

8 Answers 8

This may help someone. Make sure the history package version are compatible with the react-router-dom .

This combination didn’t work for me:

history: 5.0.0 with react-router-dom: 5.2.0

This combo did:

history: 4.10.1 with react-router-dom 5.2.0

You’re creating new history each time you invoke createHistory() . If you’re using react-router-dom you can simply use the withRouter HOC that’ll supply the history object to the component via a prop . You’ll then utilize history.push(‘/’) , or if it’s in a class component , this.props.history.push(‘/’) and so on.

routes (define history within routes )

components/Header.js (we want to access history , however, sometimes we have to use withRouter because components like Header don’t reside within a HOC, so it’s unaware of our routing)

components/Home.js (a component like Home is aware of routing and has the history object already passed in via the HOC, so withRouter isn’t required)

Same concept as above, however, if you don’t want to use withRouter , then you can simply create a history instance that’ll be shared across your components that need it. You’ll import this history instance and navigate with history.push(‘/’); and so on.

history (define history in its own file)

routes (import history into routes )

components/Header.js (import history into Header )

components/Home.js (is still aware of routing and has the history object already passed in via the HOC, so importing history isn’t required, but you can still import it if you wanted to — just don’t deconstruct history in the Home ‘s function parameters)

But you might be thinking, what about BrowserRouter ? Well, BrowserRouter has it’s own internal history object. We can, once again, use withRouter to access its history . In this case, we don’t even need to createHistory() at all!

Источник

Почему в ReactJS не происходит рендеринг компонента при history.push?

Почему не происходит рендеринг компонента Login после того, как был запушин новый URL /user/login при помощи history.push? А вот при явном запросе URL /user/login — компонент Login рендериться как нужно.

  • Вопрос задан более трёх лет назад
  • 2139 просмотров

Все заработало после того как я поменял экспорт App

Вариант, который был и НЕ работал:

Вариант, который заставил всё работать так, как нужно:

Видимо суть заключается в том, что withRouter это функция высшего порядка и в данном случае ее надо применять уже к результату функции connect.

connect — тоже функция высшего порядка

хорошо, что все решилось. решение, правда, в очередной раз доказывает, что библиотеки эти — не очень

Не обратил внимания, что вы наоборот обернули. Все это есть в документации. Об истинных причинах можете почитать там же.

Павло Пономаренко, это лишь говорит о том, что Dev Fun либо совсем не читал документацию, либо делал это не внимательно. А там все есть.

каждая из которых хочет быть первой

Я так понимаю, что стейт у вас не обновляется, по сути. Попробуйте сделать специальную обертку, которая будет не только history изменять, но и еще дополнительный state в корневом элементе. Как-то так:

Dev Fun, если вы знаете в чем проблема и как ее правильно решать — зачем создали вопрос?

Источник

React-router v4 this.props.history.push(. ) not working

I’m trying to route programatically using this.props.history.push(..) but it doesn’t seem to work.

Here’s the router:

In CustomerList, a list of customers is rendered. Clicking on a customer (li) should make the application route to Customer:

The code is partial but illustrates perfectly the situation. What happens is that the browser’s address bar changes accordingly to history.push(..), but the view does not update, Customer component is not rendered and CustomersList is still there. Any ideas?

14 Answers 14

So I came to this question hoping for an answer but to no avail. I have used

In the same project and it worked as expected. Upon further experimentation and some comparing and contrasting, I realized that this code will not run if it is called within the nested component. Therefore only the rendered page component can call this function for it to work properly.

Find Working Sandbox here

  • history: v4.7.2
  • react: v16.0.0
  • react-dom: v16.0.0
  • react-router-dom: v4.2.2

It seems things have changed around a bit in the latest version of react router. You can now access history via the context. this.context.history.push(‘/path’)

You can try to load the child component with history. to do so, pass ‘history’ through props. Something like that:

For me (react-router v4, react v16) the problem was that I had the navigation component all right:

Both using either

The behavior was still the same — the URL in browser changed but wrong components were rendered, the router was called with the same old URL.

The culprit was in the router definition. I had to move the MainMenu component as a child of the Router component!

You can get access to the history object’s properties and the closest ‘s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

Seems like an old question but still relevant.

I think it is a blocked update issue.

The main problem is the new URL (route) is supposed to be rendered by the same component( Costumers ) as you are currently in (current URL).

So solution is rather simple, make the window url as a prop, so react has a chance to detect the prop change (therefore the url change), and act accordingly.

A nice usecase described in the official react blog called Recommendation: Fully uncontrolled component with a key.

So the solution is to change from render()

So whenever the location changed by react-router, the component got scrapped (by react) and a new one gets initiated with the right values (by react).

Oh, and pass the location as prop to the component( Costumers ) where the redirect will happen if it is not passed already.

Источник

Почему после history.push() не рендерится компонент?

происходит push, url меняется но компонент не рендерится.Но если перезагрузить страницу то рендер срабатывает.

В чем проблема?
Спасибо

  • Вопрос задан более двух лет назад
  • 1228 просмотров

Антон Спирин, «react-router-dom»: «^5.0.0»,
больше нигде не пользовался push,
Если выводить console.log( history ); в productSinglePage получаю следующее

то есть id передается корректно

происходит push, url меняется но компонент не рендерится.Но если перезагрузить страницу то рендер срабатывает.

Дмитрий, вот эта строчка то у вас вызывается когда вы вызываете history.push?:

и появляются ли ошибки в консоли после клика по ссылке?

Дмитрий, вы все делаете неправильно. Вы должны использовать для роутинга и запросов к API slug товара. Это такая строка, которая должна быть уникальной, лежать в базе и быть основана на названии. Например:

Тогда не надо будет ничего передавать кроме пути.

Источник

Читайте также:  Как отремонтировать дренажный насос с поплавком
Оцените статью