在我的组件中,我收到一个数组对象(仅 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)。
- 有没有更好的方法来解决这个问题?