所以,我仍然是React的初学者,我正试图保存“数量”的状态值
constructor(props){
super(props);
this.state = {
visible: false,
selected: false,
quantity: ""
}
this.toggleMenu = this.toggleMenu.bind(this);
}
我想将此数据传递给链接到此组件的父组件的组件,并防止丢失数据,如果我回去。
<Link to={`/itemSelection/${sessionStorage.getItem("")}/checkout`}>PROCEED</Link>
______________________________________________________-
EDITED
所以父组件是ItemSelection里面我导入Item组件并映射我从api得到的一些数据。
<div className="row">
{this.state.items.map(i => <Item name={i.name} quantity={i.quantity} />)}
</div>
我传给Item的数量是我从api得到的全部数量。
在Item组件里面
constructor(props){
super(props);
this.state = {
visible: false,
selected: false,
quantity: ""
}
this.toggleMenu = this.toggleMenu.bind(this);
}
这里的数量是我为每个选择的项目选择的数量。当我点击结账组件的链接时,我丢失了这些数据,如果我回到itemSelection组件,我发现这些数据也会丢失。因此,我希望将每个项目的数量传递给结帐组件,并防止丢失数据,如果我再次返回到itemSelection组件。希望这种澄清是有道理的。
你必须将你的状态提升到路由之上。 IE:
// ParentComponent hold state and pass it as props in RENDER props to route A and route B
<ParentComponent>
<Switch>
<Route ... render={props => <MycomponentA quantity={this.props.quantity}} />} /> // Route A
<Route ... render={props => <MycomponentA quantity={this.props.quantity}}/> // Route B
</Switch>
</ParentComponent>