如何在构造函数之外使用构造函数值? [英] How to use constructor value outside constructor?

查看:102
本文介绍了如何在构造函数之外使用构造函数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的组件中,我收到一个数组对象(仅3个对象).我想分别显示它们,还想向它们添加一个onClick事件,以便当用户单击它们中的任何一个时,我可以为每种情况呈现不同的组件.
现在的问题是我正在访问构造函数中的变量,而其余组件不在该范围内.在这种情况下该怎么办?

In my component I'm receiving an array object(3 objects only). I want to display them separately and also want to add a onClick event to them so that when user clicks any of them I can render different component for each case.
Now the problem is I am accessing the variables inside constructor and rest of the component is outside that scope. What to do in this situation??

import React, { Component } from 'react';
import '../App.css';
import {withRouter} from 'react-router';
import MonthToDate from './monthtodate';
import QuarterToDate from './quartertodate';
import YearToDate from './yeartodate';
class Dashboard extends Component {

  constructor(props){
    super(props);
    if(this.props.location && this.props.location.state){
      console.log(this.props.location.state.values.o1)
      var o1=this.props.location.state.values.o1;
      var o2=this.props.location.state.values.o2;
      var o3=this.props.location.state.values.o3;
    }
  }
  callMonth = () => { this.props.history.push({pathname: '/monthtodate'}) };
  callQuarter = () => { this.props.history.push({pathname: '/quartertodate'}) };
  callYear = () => { this.props.history.push({pathname: '/yeartodate'}) };

  render() {
    return (
      <div>
        <div onClick:{this.callMonth}>
          <p>MonthToDate: {o1}</p>
        </div>
        <div onClick:{this.callQuarter}>
          <p>QuarterToDate: {o2}</p>
        </div>
        <div onClick:{this.callYear}>
          <p>YearToDate: {o3}</p>
        </div>
      </div>
    );
  }
}

export default Dashboard;          

注意::{this.props.location.state.values.o1}在内部return中不起作用,因为如果条件为idk,则要求这样做. 经过大量的谷歌搜索后,我开始知道反应中没有类变量.相反,它具有Context,但官方文档说这是一个实验性的API,它可能会在React的未来版本中破坏.

NOTE: Doing {this.props.location.state.values.o1} doesn't work inside return as it requires that if condition idk why. After much Googling I came to know that there is no class variable in react. Instead it has Context but it's official docs say It is an experimental API and it is likely to break in future releases of React.

上述组件由登录组件调用,即login.js,如下所示:

The above component is called by Login component ie login.js which is as below:

import React, { Component } from 'react';
import '../App.css';
import Dashboard from './dashboard';
import {withRouter} from 'react-router';
var axios = require('axios');

class Login extends Component {
  constructor(props){
    super(props);
    //this.state = {isToggleOn: true};
    this.loadDashboard = this.loadDashboard.bind(this);
    this.handleOnSubmit = this.handleOnSubmit.bind(this);
    this.setData = this.setData.bind(this);
    this.state = {values:null}
  }
  setData(data){
    this.setState({values:data});
    //console.log(data);
    this.props.history.push({
      pathname: '/dashboard',
      state: { values: data }
  })
  }
  loadDashboard(token){
    console.log(token);
    axios({
      method:'get',
      url:'http://localhost:3000/api/dashboard',
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
     .then( (response) => {
      // console.log(response.data);
      //  this.props.history.push('/dashboard',this.state.values);
       this.setData(response.data);
     })
     .catch(function (error) {
       console.log("Error in loading Dashboard "+error);
     });
  }

  handleOnSubmit = () => {
     //console.log("submittwed");
     axios({
       method:'post',
       url:'http://localhost:3000/authenticate',
       data: {
         email: 'test@mail.com',
         password: 'apple'
       },
     })
      .then((response) => {
        var token = response.data.auth_token;
      //  console.log(token);
        this.loadDashboard(token);
      })
      .catch(function (error) {
        console.log("Error in login "+error);
      });
   }

  render() {
    return (
      <div>
         Username: <input type="email" name="fname" /><br />
         Password: <input type="password" name="lname" /><br />
         <button onClick={this.handleOnSubmit}>LOG IN</button>     
      </div>
    );
  }
}

export default Login;       

  • 如何在整个课程中传递变量. (注意:我不想将来更改它,只想显示它,所以没有REDUX请).
  • 有没有更好的方法来解决这个问题?
  • 推荐答案

    您可以使用本地组件状态,如下所示:

    You can use local component state as below:

    constructor(props){
        super(props);
        if(this.props.location && this.props.location.state){
          this.state = {
            o1 : this.props.location.state.values.o1,
            o2 : this.props.location.state.values.o2,
            o3 : this.props.location.state.values.o3
          }
        }
      }
    

    然后在渲染器或以下所需的任何方法中使用它:

    Then use it in your render or whatever method you need as below:

    render() {
        return (
          <div>
            <div onClick={()=>{this.callMonth()}}>
              <p>MonthToDate: {this.state.o1}</p>
            </div>
            <div onClick={()=>{this.callQuarter()}}>
              <p>QuarterToDate: {this.state.o2}</p>
            </div>
            <div onClick={()=>{this.callYear()}}>
              <p>YearToDate: {this.state.o3}</p>
            </div>
          </div>
        );
      }
    

    希望这会有所帮助.

    这篇关于如何在构造函数之外使用构造函数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆