如何在构造函数之外使用构造函数值?

IT技术 reactjs ecmascript-6
2021-05-10 12:07:07

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

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 内不起作用,因为它需要 if 条件 idk 为什么。经过多次谷歌搜索,我开始知道react中没有类变量。相反,它有,Context但官方文档说它是一个实验性的 API,它可能会在 React 的未来版本中崩溃

上述组件由 Login 组件调用,即login.js如下:

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 pls)。
  • 有没有更好的方法来解决这个问题?
2个回答

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

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

然后在您的渲染或您需要的任何方法中使用它,如下所示:

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>
    );
  }

希望这可以帮助。

您应该使用this关键字来将对象存储在class.
所以你可以做这样的事情,例如:

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

并以相同的方式访问它:

<div onClick:{this.callMonth}>
   <p>MonthToDate: {this.o1}</p>
</div>

话虽如此,我认为您应该重新考虑这种方法,也许可以直接从 props 访问这些值,或者创建一个state并将它们存储在那里。
无论哪种方式,您都应该更新生命周期方法中的对象componentWillReceiveProps