【问题标题】:How to save props or state values without using Redux如何在不使用 Redux 的情况下保存 props 或 state 值
【发布时间】:2018-09-11 12:22:19
【问题描述】:

所以,我仍然是 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>

我传递给 Item 的数量是我从 api 获得的全部数量。

Item 组件内部

constructor(props){
        super(props);
        this.state = {
          visible: false,
          selected: false,
          quantity: ""
        }
        this.toggleMenu = this.toggleMenu.bind(this);
    }

这里的数量是我为我选择的每件商品选择的数量。当我单击结帐组件的链接时,我丢失了这些数据,如果我返回 itemSelection 组件,我发现这些数据也丢失了。因此,我想将每个项目的这个数量传递给结帐组件,并在我再次返回 itemSelection 组件时防止丢失数据。 希望这个澄清是有意义的。

【问题讨论】:

    标签: reactjs ecmascript-6 react-props


    【解决方案1】:

    您必须将您的状态提升到路由之上。即:

    // 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>

    【讨论】:

    • 拥有完整的结构很难看出你需要提升多少状态。在您的代码中,我看到一个 所以我想您正在使用 react-router (v4?)。您必须利用组件的状态包含路由器和路由。当一个组件被重新挂载时,它的状态也会被重置,所以你必须将你的状态置于不受路由更改影响的级别。继续朝着这个方向前进,因为如果您不使用 redux 并且您将考虑另一种模式,那么这可能是一种反模式。参考:reactjs.org/docs/lifting-state-up.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 2016-10-17
    • 1970-01-01
    • 2011-12-22
    • 2021-12-17
    • 2013-02-11
    • 1970-01-01
    相关资源
    最近更新 更多