在index.js中加入BroswerRouter
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import {
BrowserRouter} from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
, document.getElementById('root'));
registerServiceWorker();
在App.js中设置每个component的path
class App extends Component {
render () {
return (
<div>
<Layout>
<Switch>
<Route path="/checkout" component={
Checkout}/>
<Route path="/" exact component={
BurgerBuilder}/>
</Switch>
</Layout>
</div>
);
}
}
Navigating to the checkout page
讲bugerbuilder中的continue事件改为进入/checkout地址
history.push为往栈中压入新地址,即进入新地址;
purchaseContinueHandler = () => {
this.props.history.push('/checkout');
}
将Route的props传入子元素的子元素的方法
import {
withRoute} from 'react-router-dom';
const component=()=>{
}
export default withRoute(component);
Navigate Back & to page
histroy.goBack()
checkoutCancelledHandler=()=>{
this.props.history.goBack();
}
history.replace(url)
checkoutContinuedHandler=()=>{
this.props.history.replace('/check/contact-data');
}
Passing ingredients via Quary Params
将要传递的内容变为用&和=连接的string,
将此string’传入history.push中的search元素中;
const queryParams= [];
for(let i in this.state.ingredients){
queryParams.push(encodeURIComponent(i)+'='+encodeURIComponent(this.state.ingredients[i])); //将code转为可用在url的形式
};
const queryString = queryParams.join('&');
this.props.history.push({
pathname:'/checkout',
search: '?'+queryString
});
在该pathname的compnent中,对获取的url进行解析;
用URLSearchParams(this.props.location.search)解析url;
遍历该entries(),得到参数为[‘salad’,‘1’]的array;
放入新建的ingredients中,用setstate改变state,即可;
componentDidMount(){
const query = new URLSearchParams(this