Can't get React Router's 4 Link working - reactjs

Here is the code of component where problem occurs:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Redirect, Link, withRouter } from 'react-router-dom'
import * as actions from 'actions';
class DashBoard extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.dispatch(actions.deleteItems());
this.props.dispatch(actions.fetchItems());
}
render() {
let { items } = this.props;
let key = 0;
let renderItems = () => {
if (!items) {
return
}
return items.map((item) => {
let { action, author } = item.logs[item.logs.length - 1];
return (
<div className="dashboard-item">
<h3>{item.name}</h3>
<div className="info-container">
<span>Amount: {item.number}</span>
<span>{item.state}</span>
</div>
<span className="created">{`${action} by ${author}`}</span>
<span className="last-log">{`Last log: ${item.logs[0].action} by ${item.logs[0].author}`}</span>
<div className="buttons">
<Link to='/'>Edit</Link>
<Link to={`/items/${item.id}/edit`}>Delete</Link>
</div>
</div>
);
})
}
if (this.props.auth.token) {
return (
<div className="dashboard-container">
{renderItems()}
</div>
);
} else {
this.props.dispatch(actions.setError('You must log in.'))
return <Redirect to='/' />
}
}
}
export default withRouter(connect(
(state) => {
return state;
}
)(DashBoard));
I got Redirect working, but clicking a link just changes url in browser, and actually I still see my dashboard component. If I enter localhost:3000/items/random id/edit i get right result. Creating and clicking a link does nothing. Nothing changes visually except url bar. withRouter hack seems to not work for me. However entering url directly works. How can I fix this?
EDIT : Route definition
import React, { Component } from 'react';
import { Route, Link } from 'react-router-dom';
import { connect } from 'react-redux';
import Home from 'Home';
import Dashboard from 'Dashboard';
import EditItemForm from 'EditItemForm';
import NewItemForm from 'NewItemForm';
export class Main extends Component {
constructor(props) {
super(props);
}
render() {
let { auth, error } = this.props;
let renderError = () => {
if (error) {
return (
<div className="error">
<p>{error}</p>
</div>
)
} else {
return (<div></div>)
}
}
return (
<div>
{renderError()}
<Route exact={true} path="/" component={Home} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/items/:id/edit" component={EditItemForm} />
<Route path="/items/new" component={NewItemForm}/>
</div>
);
}
}
export default connect(
(state) => {
return state;
}
)(Main);
EDIT #2: Figured out that clicking a Link even doesnt change pathname in route > location > pathname if look into React DevTools

It seems to me that there is nothing wrong with your code relative to the use of React Router that you shown here.
I would suggest that you simplify your application and you post the main Router component, it should be fine because you see your dashboard, but it can help.
Try to do a fake hello word route and do the transition from your dashboard to there..
Usually the most likely thing you could have here is a nested component that is blocking the update of the route. Usually putting withRouter in every connected component should work. Alternatively you could try to add withRouter in every component that is nested with the route.
I think there should be a elegant why to solve this, but maybe this can help you know where this problem comes from.
Then try to check if your third party libraries support RR4.
Good luck!

I think that you may need to use a switch above all routes in a component because even I had a similar issue before. however that works in react router v3. Hope this helps u :) cheers
React Router 4
React Router v4 Unofficial Migration Guide

So I just rolled back to v3. Thank you guys for trying to help!

Related

Redirect to login page after logout

I'm kind of new to React stuff, I've been playing with it for like a week, and I'm stuck at pretty simple thing I think.
After user clicks "logout" I want the function logOut to also redirect him to other page (atm login page, cause its the only other page I've got). However, using navigate, I am having this error about Hooks.
Line 13:21: React Hook "useNavigate" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function
I've tried to workaround this however I don't think I fully understand whats the matter here. If anyone could simply point to me, what should I re-write to get my code going, I would be grateful.
My App.js:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom';
import './App.css';
import RegistrationForm from './registry/Register';
import LoginForm from './registry/Login';
import WelcomeBack from './pages/Main';
import { useNavigate } from 'react-router-dom';
class App extends Component {
}
render() {
const nav = useNavigate();
function logOut() {
localStorage.removeItem("jwt");
nav("/login");
}
function isLoggedIn() {
const tokenValue = localStorage.getItem("jwt");
if (tokenValue != null) {
return true;
}
//here navigate to '/login'
return false;
}
return (
<Router>
<div>
<div class="topnav" id="myTopnav">
Home
About
Register
Login
<div className="logout" >
<a href="#" class="split" onClick={logOut}>Logout</a>
</div>
<a href="javascript:void(0);" class="icon" onClick={myFunction}>
<i class="fa fa-bars"></i>
</a>
</div>
<Routes>
<Route path='/register' element={<RegistrationForm />}/>
<Route path='/login' element={<LoginForm />} />
<Route path='/' element={<WelcomeBack />} />
</Routes>
</div>
</Router>
);
}
}
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
}
else {
x.className = "topnav";
}
}
export default App;
Hooks are not working in the class component, if u want to use you can wrap it in a HOC.
function withNavigation(Component) {
return props => <Component {...props} navigate={useNavigate()} />;
}
and then
class BlogPost extends React.Component {
redirect(){
this.props.navigate('/url')
}
render() {
// ...
}
}
export default withNavigation(BlogPost);
check this issue for more information Github Issue
first thing you can't use react hooks ( useNavigate ) inside class component, instead you can use withRouter in class component.
https://v5.reactrouter.com/web/api/withRouter
second thing, you forgot to put the code between the curly braces
you should do it like this:
class App extends Component {
...
// put your code here between the curly braces
}

Reactjs - how to pass props to Route?

I’m learning React Navigation using React-Router-Dom. I have created a simple app to illustrate the problem:
Inside App.js I have a Route, that points to the url “/” and loads the functional Component DataSource.js.
Inside DataSource.js I have a state with the variable name:”John”. There is also a buttonwith the onclick pointing to a class method that’s supposed to load a stateless component named ShowData.js using Route.
ShowData.js receives props.name.
What I want to do is: when the button in DataSource.js is clicked, the url changes to “/showdata”, the ShowData.js is loaded and displays the props.name received by DataSource.js, and DataSource.js goes away.
App.js
import './App.css';
import {Route} from 'react-router-dom'
import DataSource from './containers/DataSource'
function App() {
return (
<div className="App">
<Route path='/' component={DataSource}/>
</div>
);
}
export default App;
DataSource.js
import React, { Component } from 'react';
import ShowData from '../components/ShowData'
import {Route} from 'react-router-dom'
class DataSource extends Component{
state={
name:' John',
}
showDataHandler = ()=>{
<Route path='/showdata' render={()=><ShowData name={this.state.name}/>}/>
}
render(){
return(
<div>
<button onClick={this.showDataHandler}>Go!</button>
</div>
)
}
}
export default DataSource;
ShowData.js
import React from 'react';
const showData = props =>{
return (
<div>
<p>{props.name}</p>
</div>
)
}
export default showData;
I have tried the following, but, even though the url does change to '/showdata', the DataSource component is the only thing being rendered to the screen:
DataSource.js
showDataHandler = ()=>{
this.props.history.push('/showdata')
}
render(){
return(
<div>
<button onClick={this.showDataHandler}>Go!</button>
<Route path='/showdata' render={()=>{<ShowData name={this.state.name}/>}}/>
</div>
)
}
I also tried the following but nothing changes when the button is clicked:
DataSource.js
showDataHandler = ()=>{
<Route path='/showdata' render={()=>{<ShowData name={this.state.name}/>}}/>
}
render(){
return(
<div>
<button onClick={this.showDataHandler}>Go!</button>
</div>
)
}
How can I use a nested Route inside DataSource.js to pass a prop to another component?
Thanks.
EDIT: As user Sadequs Haque so kindly pointed out, it is possible to retrieve the props when you pass that prop through the url, like '/showdata/John', but that's not what I'd like to do: I'd like that the url was just '/showdata/'.
He also points out that it is possible to render either DataSource or ShowData conditionally, but that will not change the url from '/' to '/showdata'.
There were multiple issues to solve and this solution worked as you wanted.
App.js should have all the routes. I used Route params to pass the props to ShowData. So, /showdata/value would pass value as params to ShowData and render ShowData. And then wrapped the Routes with BrowserRouter. And then used exact route to point / to DataSource because otherwise DataSource would still get rendered as /showdata/:name has /
DataSource.js will simply Link the button to the appropriate Route. You would populate DataSourceValue with the appropriate value.
ShowData.js would read and display value from the router prop. I figured out the object structure of the router params from a console.log() of the props object. It ended up being props.match.params
App.js
import { BrowserRouter as Router, Route } from "react-router-dom";
import DataSource from "./DataSource";
import ShowData from "./ShowData";
function App() {
return (
<div className="App">
<Router>
<Route exact path="/" component={DataSource} />
<Route path="/showdata/:name" component={ShowData} />
</Router>
</div>
);
}
export default App;
DataSource.js
import React, { Component } from "react";
import ShowData from "./ShowData";
class DataSource extends Component {
state = {
name: " John",
clicked: false
};
render() {
if (!this.state.clicked)
return (
<button
onClick={() => {
this.setState({ name: "John", clicked: true });
console.log(this.state.clicked);
}}
>
Go!
</button>
);
else {
return <ShowData name={this.state.name} />;
}
}
}
export default DataSource;
ShowData.js
import React from "react";
const ShowData = (props) => {
console.log(props);
return (
<div>
<p>{props.name}</p>
</div>
);
};
export default ShowData;
Here is my scripts on CodeSandbox. https://codesandbox.io/s/zen-hodgkin-yfjs6?fontsize=14&hidenavigation=1&theme=dark
I figured it out. At least, one way of doing it, anyway.
First, I added a route to the ShowData component inside App.js, so that ShowData could get access to the router props. I also included exact to DataSource route, so it wouldn't be displayed when ShowData is rendered.
App.js
import './App.css';
import {Route} from 'react-router-dom'
import DataSource from './containers/DataSource'
import ShowData from './components/ShowData'
function App() {
return (
<div className="App">
<Route exact path='/' component={DataSource}/>
{/* 1. add Route to ShowData */}
<Route path='/showdata' component={ShowData}/>
</div>
);
}
export default App;
Inside DataSource, I modified the showDataHandler method to push the url I wanted, AND added a query param to it.
DataSource.js
import React, { Component } from 'react';
class DataSource extends Component{
state={
name:' John',
}
showDataHandler = ()=>{
this.props.history.push({
pathname:'/showdata',
query:this.state.name
})
}
render(){
return(
<div>
<button onClick={this.showDataHandler}>Go!</button>
</div>
)
}
}
export default DataSource;
And, finally, I modified ShowData to be a Class, so I could use state and have access to ComponentDidMount (I guess is also possible to use hooks here, if you don't want to change it to a Class).
Inside ComponentDidMount, I get the query param and update the state.
ShowData.js
import React, { Component } from 'react';
class ShowData extends Component{
state={
name:null
}
componentDidMount(){
this.setState({name:this.props.location.query})
}
render(){
return (
<div>
<p>{this.state.name}</p>
</div>
)
}
}
export default ShowData;
Now, when I click the button, the url changes to '/showdata' (and only '/showdata') and the prop name is displayed.
Hope this helps someone. Thanks.

React-router custom prop not passing to component. ternary operator not working correctly

In React i have my App.js page where i keep my states. I'm importing user1.js component to App.js, and in user1.js component i have a link button that takes me to path /user2.
When i click the button, React will set state property called testValue to true and in user2.js page ternary operator should choose the first value - test works because of that. But for some reason it does not work.
Any help?
APP.JS
import React, { Component } from 'react';
import './App.css';
import User1 from './components/user1';
class App extends Component {
constructor(props){
super(props);
this.state = {
testValue:false
};
}
change = () => {
this.setState({
testValue:true
},() => {
console.log(this.state.testValue)
});
}
render() {
return (
<div className="App">
<User1 change={this.change}/>
</div>
);
}
}
export default App;
USER1.JS
import React from 'react';
import { BrowserRouter, Route, Switch, Link } from 'react-router-dom';
import User2 from './user2.js';
const User1 = (props) => {
return(
<BrowserRouter>
<div>
<Link to ="/user2">
<button onClick={props.change}>Next page</button>
</Link>
<Switch>
<Route path="/user2" exact component={User2}/>
</Switch>
</div>
</BrowserRouter>
); // end of return
};
export default User1;
USER2.JS
import React from 'react';
const User2 = (props) => {
console.log(props)
return(
<div>
{props.testValue ?
<p>test works</p>
:
<p>test does not work</p>
}
</div>
);
};
export default User2;
This is what i expected - test works
This is what i got - test does not work
You want to pass a custom property through to a component rendered via a route. Recommended way to do that is to use the render method.
<Route path="/user2" exact render={(props) => <User2 {...props} testValue={true} />} />
I think a valid inquiry here would be what are you wanting to pass through as an extra prop? whats the use case here? You may be trying to pass data in a way you shouldn't (context would be nice :D).

React router v4 not working with Redux

Developing a React application using React router v4. All worked well until I introduced Redux in my app. Since then on click of links to change route the browser url changes but the component corresponding to the route is not getting loaded. It works well if I comment out Redux code. What could be causing this? Here is my code for routing:
import React, { Component } from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import LeftSubDefault from './../components/left-sub-default.component';
import LeftSubOne from './../components/left-sub-one.component';
import LeftSubTwo from './../components/left-sub-two.component';
import { withRouter } from 'react-router-dom';
import { connect } from "react-redux";
import { goToLeftDefault, goToLeftOne, goToLeftTwo } from "./../actions/leftRouteActions.js";
class LeftComponent extends Component {
render() {
return (
<div className="col-xs-6">
<p>
Current sub route: {this.props.currentRoute}
</p>
<ul>
<li onClick={this.props.goToDefault}><Link to={'/'}>Go To Default</Link></li>
<li onClick={this.props.goToSub1}><Link to={'/left-sub1'}>Go To One</Link></li>
<li onClick={this.props.goToSub2}><Link to={'/left-sub2'}>Go To Two</Link></li>
</ul>
<Switch>
<Route exact path='/' component={LeftSubDefault} />
<Route exact path='/left-sub1' component={LeftSubOne} />
<Route exact path='/left-sub2' component={LeftSubTwo} />
</Switch>
</div>
);
}
}
const mapStateToProps = (store) => {
return {
currentRoute: store.routes.currentRoute
};
}
const mapDispatchToProps = (dispatch) => {
return {
goToDefault: () => {
dispatch(goToLeftDefault())
},
goToSub1: () => {
dispatch(goToLeftOne())
},
goToSub2: () => {
dispatch(goToLeftTwo())
}
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(LeftComponent));
PS: I get no error in console. The code runs clean just components don't load. Here is a similar thread on github: 4671. I have seen lot of threads on various sites but none has the solution for this issue.
Hah, now I'm making a project with react-router and redux too =).
Look at the official documentation about redux integration https://reacttraining.com/react-router/web/guides/redux-integration.
I think the main point is order of withRouter and connect Hocs.
The problem is that Redux implements shouldComponentUpdate and there’s no indication that anything has changed if it isn’t receiving props from the router. This is straightforward to fix. Find where you connect your component and wrap it in withRouter.
From the official docs.
UPD
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
class Home extends React.Component {...}
export default withRouter(
connect(mapStateToPropsFunc)(Home)
);
I'm using react-router-dom v4.1.1. It is working for me. Here is my Demo
import React from 'react';
import Reducer1 from 'yourReducer1';
import Reducer2 from 'yourReducer2';
import {
Route,
Switch as RouterSwitch
} from 'react-router-dom';
const App =()=> (
<RouterSwitch>
<Route path="/link1" exact component={Reducer1}/>
<Route path="/link2" exact component={Reducer2}/>
</RouterSwitch>
);
export default App;
Hope it is helpful for you ^^

React router Link not causing component to update within nested routes

This is driving me crazy. When I try to use React Router's Link within a nested route, the link updates in the browser but the view isn't changing. Yet if I refresh the page to the link, it does. Somehow, the component isn't updating when it should (or at least that's the goal).
Here's what my links look like (prev/next-item are really vars):
<Link to={'/portfolio/previous-item'}>
<button className="button button-xs">Previous</button>
</Link>
<Link to={'/portfolio/next-item'}>
<button className="button button-xs">Next</button>
</Link>
A hacky solution is to manaully call a forceUpate() like:
<Link onClick={this.forceUpdate} to={'/portfolio/next-item'}>
<button className="button button-xs">Next</button>
</Link>
That works, but causes a full page refresh, which I don't want and an error:
ReactComponent.js:85 Uncaught TypeError: Cannot read property 'enqueueForceUpdate' of undefined
I've searched high and low for an answer and the closest I could come is this: https://github.com/reactjs/react-router/issues/880. But it's old and I'm not using the pure render mixin.
Here are my relevant routes:
<Route component={App}>
<Route path='/' component={Home}>
<Route path="/index:hashRoute" component={Home} />
</Route>
<Route path="/portfolio" component={PortfolioDetail} >
<Route path="/portfolio/:slug" component={PortfolioItemDetail} />
</Route>
<Route path="*" component={NoMatch} />
</Route>
For whatever reason, calling Link is not causing the component to remount which needs to happen in order to fetch the content for the new view. It does call componentDidUpdate, and I'm sure I could check for a url slug change and then trigger my ajax call/view update there, but it seems like this shouldn't be needed.
EDIT (more of the relevant code):
PortfolioDetail.js
import React, {Component} from 'react';
import { browserHistory } from 'react-router'
import {connect} from 'react-redux';
import Loader from '../components/common/loader';
import PortfolioItemDetail from '../components/portfolio-detail/portfolioItemDetail';
import * as portfolioActions from '../actions/portfolio';
export default class PortfolioDetail extends Component {
static readyOnActions(dispatch, params) {
// this action fires when rendering on the server then again with each componentDidMount.
// but not firing with Link...
return Promise.all([
dispatch(portfolioActions.fetchPortfolioDetailIfNeeded(params.slug))
]);
}
componentDidMount() {
// react-router Link is not causing this event to fire
const {dispatch, params} = this.props;
PortfolioDetail.readyOnActions(dispatch, params);
}
componentWillUnmount() {
// react-router Link is not causing this event to fire
this.props.dispatch(portfolioActions.resetPortfolioDetail());
}
renderPortfolioItemDetail(browserHistory) {
const {DetailReadyState, item} = this.props.portfolio;
if (DetailReadyState === 'WORK_DETAIL_FETCHING') {
return <Loader />;
} else if (DetailReadyState === 'WORK_DETAIL_FETCHED') {
return <PortfolioItemDetail />; // used to have this as this.props.children when the route was nested
} else if (DetailReadyState === 'WORK_DETAIL_FETCH_FAILED') {
browserHistory.push('/not-found');
}
}
render() {
return (
<div id="interior-page">
{this.renderPortfolioItemDetail(browserHistory)}
</div>
);
}
}
function mapStateToProps(state) {
return {
portfolio: state.portfolio
};
}
function mapDispatchToProps(dispatch) {
return {
dispatch: dispatch
}
}
export default connect(mapStateToProps, mapDispatchToProps)(PortfolioDetail);
PortfolioItemDetail.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Gallery from './gallery';
export default class PortfolioItemDetail extends React.Component {
makeGallery(gallery) {
if (gallery) {
return gallery
.split('|')
.map((image, i) => {
return <li key={i}><img src={'/images/portfolio/' + image} alt="" /></li>
})
}
}
render() {
const { item } = this.props.portfolio;
return (
<div className="portfolio-detail container-fluid">
<Gallery
makeGallery={this.makeGallery.bind(this)}
item={item}
/>
</div>
);
}
}
function mapStateToProps(state) {
return {
portfolio: state.portfolio
};
}
export default connect(mapStateToProps)(PortfolioItemDetail);
gallery.js
import React, { Component } from 'react';
import { Link } from 'react-router';
const Gallery = (props) => {
const {gallery, prev, next} = props.item;
const prevButton = prev ? <Link to={'/portfolio/' + prev}><button className="button button-xs">Previous</button></Link> : '';
const nextButton = next ? <Link to={'/portfolio/' + next}><button className="button button-xs">Next</button></Link> : '';
return (
<div>
<ul className="gallery">
{props.makeGallery(gallery)}
</ul>
<div className="next-prev-btns">
{prevButton}
{nextButton}
</div>
</div>
);
};
export default Gallery;
New routes, based on Anoop's suggestion:
<Route component={App}>
<Route path='/' component={Home}>
<Route path="/index:hashRoute" component={Home} />
</Route>
<Route path="/portfolio/:slug" component={PortfolioDetail} />
<Route path="*" component={NoMatch} />
</Route>
Could not get to the bottom of this, but I was able to achieve my goals with ComponentWillRecieveProps:
componentWillReceiveProps(nextProps){
if (nextProps.params.slug !== this.props.params.slug) {
const {dispatch, params} = nextProps;
PortfolioDetail.readyOnActions(dispatch, params, true);
}
}
In other words, for whatever reason when I use React Router Link to link to a page with the SAME PARENT COMPONENT, it doesn't fire componentWillUnMount/componentWillMount. So I'm having to manually trigger my actions. It does work as I expect whenever I link to Routes with a different parent component.
Maybe this is as designed, but it doesn't seem right and isn't intuitive. I've noticed that there are many similar questions on Stackoverflow about Link changing the url but not updating the page so I'm not the only one. If anyone has any insight on this I would still love to hear it!
It's good to share the components code also. However, I tried to recreate the same locally and is working fine for me. Below is the sample code,
import { Route, Link } from 'react-router';
import React from 'react';
import App from '../components/App';
const Home = ({ children }) => (
<div>
Hello There Team!!!
{children}
</div>
);
const PortfolioDetail = () => (
<div>
<Link to={'/portfolio/previous-item'}>
<button className="button button-xs">Previous</button>
</Link>
<Link to={'/portfolio/next-item'}>
<button className="button button-xs">Next</button>
</Link>
</div>
);
const PortfolioItemDetail = () => (
<div>PortfolioItemDetail</div>
);
const NoMatch = () => (
<div>404</div>
);
module.exports = (
<Route path="/" component={Home}>
<Route path='/' component={Home}>
<Route path="/index:hashRoute" component={Home} />
</Route>
<Route path="/portfolio" component={PortfolioDetail} />
<Route path="/portfolio/:slug" component={PortfolioItemDetail} />
<Route path="*" component={NoMatch} />
</Route>
);
componentWillReceiveProps is the answer to this one, but it's a little annoying. I wrote a BaseController "concept" which sets a state action on route changes EVEN though the route's component is the same. So imagine your routes look like this:
<Route path="test" name="test" component={TestController} />
<Route path="test/edit(/:id)" name="test" component={TestController} />
<Route path="test/anything" name="test" component={TestController} />
So then a BaseController would check the route update:
import React from "react";
/**
* conceptual experiment
* to adapt a controller/action sort of approach
*/
export default class BaseController extends React.Component {
/**
* setState function as a call back to be set from
* every inheriting instance
*
* #param setStateCallback
*/
init(setStateCallback) {
this.setStateCall = setStateCallback
this.setStateCall({action: this.getActionFromPath(this.props.location.pathname)})
}
componentWillReceiveProps(nextProps) {
if (nextProps.location.pathname != this.props.location.pathname) {
this.setStateCall({action: this.getActionFromPath(nextProps.location.pathname)})
}
}
getActionFromPath(path) {
let split = path.split('/')
if(split.length == 3 && split[2].length > 0) {
return split[2]
} else {
return 'index'
}
}
render() {
return null
}
}
You can then inherit from that one:
import React from "react";
import BaseController from './BaseController'
export default class TestController extends BaseController {
componentWillMount() {
/**
* convention is to call init to
* pass the setState function
*/
this.init(this.setState)
}
componentDidUpdate(){
/**
* state change due to route change
*/
console.log(this.state)
}
getContent(){
switch(this.state.action) {
case 'index':
return <span> Index action </span>
case 'anything':
return <span>Anything action route</span>
case 'edit':
return <span>Edit action route</span>
default:
return <span>404 I guess</span>
}
}
render() {
return (<div>
<h1>Test page</h1>
<p>
{this.getContent()}
</p>
</div>)
}
}
I got stuck on this also in React 16.
My solution was as follows:
componentWillMount() {
const { id } = this.props.match.params;
this.props.fetchCategory(id); // Fetch data and set state
}
componentWillReceiveProps(nextProps) {
const { id } = nextProps.match.params;
const { category } = nextProps;
if(!category) {
this.props.fetchCategory(id); // Fetch data and set state
}
}
I am using redux to manage state but the concept is the same I think.
Set the state as per normal on the WillMount method and when the WillReceiveProps is called you can check if the state has been updated if it hasn't you can recall the method that sets your state, this should re-render your component.
I am uncertain whether it fixes the original problem, but I had a similar issue which was resolved by passing in the function callback () => this.forceUpdate() instead of this.forceUpdate.
Since no one else is mentioning it, I see that you are using onClick={this.forceUpdate}, and would try onClick={() => this.forceUpdate()}.
Try to import BrowserRouter instead of Router
import { Switch, Route, BrowserRouter as Router } from 'react-router-dom;
It worked for me after spending a couple of hours solving this issue.
I solved this by building '' custom component instead of '', and inside it I use in the method instead of :
import * as React from "react";
import {Navigate} from "react-router-dom";
import {useState} from "react";
export function ReactLink(props) {
const [navigate, setNavigate] = useState(<span/>);
return (
<div style={{cursor: "pointer"}}
onClick={() => setNavigate(<Navigate to={props.to}/>)}>
{navigate}
{props.children}
</div>
}

Resources