所以,我仍然是 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>
____
编辑
所以父组件是 ItemSelection 在它里面,我导入 Item 组件并映射我从 api 获得的一些数据。
<div className="row">
{this.state.items.map(i => <Item name={i.name} quantity={i.quantity} />)}
</div>
我传递给项目的数量是我从 API 获得的全部数量。
项目组件内部
constructor(props){
super(props);
this.state = {
visible: false,
selected: false,
quantity: ""
}
this.toggleMenu = this.toggleMenu.bind(this);
}
这里的数量是我为我选择的每个项目选择的数量。 当我单击结帐组件的链接时,我会丢失这些数据,如果我返回到itemSelection组件,我发现这些数据也会丢失。因此,我想将每个项目的这个数量传递给结帐组件,并防止在再次返回到itemSelection组件时丢失数据。 希望这个澄清是有意义的。
你必须将你的状态提升到路由之上。即:
// 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>