I am trying to switch between two pages, but ran into many problems whiling learning react router
Within my App.js
, there is a bottom, which will navigate me to Cart
when clicked.
render() {
return (
<div>
<button type="button" className="btn btn-primary Bottom-right " onClick={(e) => this.handleSubmit(e)}>
Confirmed Order
</button>
<button type="button" className="btn btn-Primary">
<Link to="/displayCart" >Show Car</Link>
</button>
</div>
);
}
}
export default App;
In my cart component, also have similar button that navigtaes me back to the App
component.
class Cart extends React.Component {
constructor(props){
super(props)
this.state={
cartData:null
}
}
componentDidMount() {
this.callApi()
.then(res => this.setState({ cartData: res.express}))
.catch(err => console.log(err));
}
callApi = async () => {
const response = await fetch('/myCart');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};
render(){
return(
<div className="col">
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to Shopping Center</h1>
</header>
</div>
<div>{ReactHtmlParser(this.state.cartData)}</div>
<button type="button Bottom-right" className="btn btn-Primary">
<Link to="/" >Keep Shopping</Link>
</button>
</div>
)
}
}
My index.js contains two components, app JS being the default component.
ReactDOM.render(
<BrowserRouter>
<switch>
<div>
<Route exact path="/displayCart" component={Cart}/>
<Route component={App} />
</div>
</switch>
</BrowserRouter>,
document.getElementById('root')
);
Now they are really flaw in many levels:
1: When I clicked show cart, instead of rendering the new view. The cart component is rendered on the top of the view with App still rendered.
2: After clicking the Show Cart , I clicked the Show App to get back to my App Component, however the console prints:
Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in Cart (created by Route)
3: If I changed the state in App
component when I get back to App
component from Cart component
, the state did not get refreshed. For example (For example, the Boolean value "purchase" in items.) When I get back from App component from Cart, the state stays true, instead, I want it to get back to the initial state.
I followed the tutorial but it is just broken. What did i do wrong