当 url 调用第二个组件时,如何将 props 从当前组件传递到另一个组件?

How can I pass props from the current component to another component when the second component is called by url?

我们可以轻松地将数据作为 props 从父组件发送到子组件,但是如果两个组件之间没有关系怎么办?

请先阅读我的上下文,以便您轻松理解我的问题。

在我的电子商务反应应用程序中,当任何新用户访问我的网站时,我想推荐用户注册。在注册过程中我保留了两个步骤。

  1. 起初我只想从一个输入字段中获取他的手机号码。当他填写字段并按下 'continue' 按钮时 -
  2. 我想带他到另一个页面(组件),从那里我可以获取他的姓名、密码等。

这里这两个组件是相互独立的。当用户点击 'continue' 按钮时,我调用 a 并将他重定向到另一个组件。

现在我的问题是如何在第一个组件中保留此手机号码并发送到第二个组件

[N.B:我不想在拨打第二条路线时url看到手机号码]

第一个组件

export default class FirstComponent extends Component {
    render() {        
        return (
            <div>                
                <input type="text" placeholder="Type Mobile number" />
                <Link to={{ pathname: '/signup' }}>
                    <button>Continue</button>
                </Link>
            </div>
        )
    }
}

第二个组件

export default class SecondComponent extends Component {
    render() {        
        return (
            <div>       
                <input type="text" placeholder="Type Mobile number" />

            </div>
        )
    }
}

路由器

<Route exact path="/signup" render={(props) => {return <SecondComponent />} }/>

点击按钮,你可以调用handleClick函数,在这个函数中你可以使用push方法来发送道具。这样您就可以更好地控制要将数据发送到其他组件的表示形式。

<button onClick={this.handleClick}>continue</button>

handleClick = () => {
    this.props.history.push({
      pathname: '/signup',
      state: { mobile: this.state.mobileNumber }
    })
}

希望对您有所帮助!!!

你可以这样做:

<Link to={{ pathname: '/signup', state: { number: 3199192910} }}>
                    <button>Continue</button>
                </Link>

您可以在注册组件中访问它,例如:

import {withRouter} from 'react-router';

 class SecondComponent extends Component {
    render() { 
      // get the number 
      console.log(this.props.location.state.number)

        return (
            <div>       
                <input type="text" placeholder="Type Mobile number" />

            </div>
        )
    }
}

export default withRouter(SecondComponent);

查看此示例,Quotes 是您应该查看的内容:

这就是 Redux 发挥作用的地方。

Redux 是一个用于管理应用程序状态的开源 JavaScript 库。

那么在 redux 中会发生什么,我们有一个叫做 store 的东西,它管理应用程序的整个状态。
我们将一些动作发送到 store,它调用一个叫做 reducer 的函数,它根据具有的动作改变 store 中的数据被派出。如果你不明白我说的话,别担心

只需观看这个 15 分钟的视频,您就会完全了解如何在您的应用程序中使用 Redux 并解决您的问题
https://www.youtube.com/watch?v=sX3KeP7v7Kg

为了深入学习,我会推荐你​​通过
https://redux.js.org/basics/basic-tutorial

现在回到你的问题,你所要做的就是创建一个存储 phone 不,当用户点击继续按钮时,向 reduce 发送一个动作来存储 phone no,因此你的 phone no 会在整个应用程序中持续存在,每当你想访问 phone 时,只需编写视频中显示的 mapstatetoprops 函数即可访问商店中的数据并在该组件中使用它

希望这能解决您的问题

当你不使用 redux 时会发生什么 当然,你发送数据作为道具但是当你刷新页面时道具会发生什么!!!!道具丢失但是当我们使用redux时我们可以保存数据。你的应用程序即使在刷新后也能按预期工作,当然还有很多其他方法可以做到这一点