如何访问状态变量或在React.js中访问另一个组件中一个组件的let,const,var变量?

问题描述 投票:0回答:1

假设我必须验证OTP ...1.我已经将axios .post()请求写到某个路由,并且路由api生成OTP并将Otp成功发送到手机号码,为此我使用了npm的SendOtp包。2.现在,我已经使用acxios的回调函数在调用组件中收到了该Otp值,并且已经将其存储在this.state对象中。3.现在,我想验证用户键入otp时来自用户的otp。4.因此,我创建了一个由单个输入类型和按钮进行验证的React组件。5.我应该如何处理这种类型的路由和变量值传递,这样我应该能够验证OTP ...而无需将otp保存在数据库中

 //Front end code:

 axios.post('http://localhost:5000/register      /verifyotp', user)
   .then(profile => {
     console.log(profile.data.OTP)

     this.setState({
       otp: profile.data.OTP
     })
     console.log(this.state.otp)
   })
   .catch(error => {
     console.log(error)
   })

 //Backend code:

 router.route('/verifyotp').post((req, res) => {
   let mobi = req.body.Mobile;
   let ot = "934723"
   sendotp.send(mobi, "NDHome", ot, (error, data) => {
     if (!error) {
       console.log("Sent sucessfully " + data);

       res.json({
         OTP: ot
       }); //verifying otp

     } else {

       console.log(error)

     }
   })
 })
reactjs
1个回答
0
投票

要在组件之间传递变量,请考虑使用redux(https://redux.js.org/introduction/getting-started)或对上下文(https://reactjs.org/docs/context.html)作出反应。通常,除非通过子组件的支持,否则组件中的状态变量/ const / let /等。不能传递给另一个。例如,在这种情况下,假设“ AnotherComponent”是在OTP进行过程中覆盖mainComponent的模态,则可以像这样传递道具:

© www.soinside.com 2019 - 2024. All rights reserved.