我是ReactJS的新手。当我单击登录按钮时,我已成功登录,这将从API获取用户数据。
为了注册用户,我使用了另一个组件的otp模态,并使用ref从loging_register组件中打开了该模态。
现在我得到:TypeError: Cannot read property 'onOpenModal
,当单击登录按钮和otp模式时,它将在注册按钮上打开。
下面是我的代码。我也在控制台中遇到以下错误:
The above error occurred in the <Otp> component:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
下面是我的login_register js代码
import React, {Component} from 'react';
import { Link,Redirect ,withRouter } from 'react-router-dom';
import PropTypes from "prop-types";
import Otp from './otp';
import axios from '../api';
export default class LoginRegister extends Component {
static contextTypes = {
router: PropTypes.object
}
constructor(props,context){
super(props,context);
this.state = {
fname:'',
lname:'',
emailaddress:'',
password:'',
mobile:'',
user:'',
login_pass:''
}
this.regi_data = this.regi_data.bind(this);
this.login_data = this.login_data.bind(this);
}
regi_data(e){
this.setState({[e.target.name] : e.target.value}
);
}
login_data(e){
this.setState({[e.target.name] : e.target.value})
}
otpModalRef = ({onOpenModal}) => {
this.showModal = onOpenModal;
}
componentDidMount(){
}
login = (e) => {
e.preventDefault();
axios.post('/api/signin', {
user:this.state.user,
password:this.state.login_pass,
})
.then(res => {
console.log(res);
this.context.router.history.push({
pathname:'/',
});
})
.catch(function (error) {
console.log(error.message);
})
}
register = (e) => {
e.preventDefault();
this.showModal();
axios.post('/api/user/add', {
firstname: this.state.fname,
lastname:this.state.lname,
email:this.state.emailaddress,
password:this.state.password,
mobile:this.state.mobile
},
)
.then(res => {
console.log(res);
})
}
&OTP js代码
import React, { Component } from 'react';
import OwlCarousel from 'react-owl-carousel';
import 'owl.carousel/dist/assets/owl.carousel.css';
import 'owl.carousel/dist/assets/owl.theme.default.css';
import { Link,Redirect ,withRouter } from 'react-router-dom';
import PropTypes from "prop-types";
import axios from 'axios';
import Modal from 'react-responsive-modal';
export default class Otp extends Component{
constructor(props){
super(props);
this.state = {
isOpen: false,
otp:''
};
this.otpdata = this.otpdata.bind(this);
}
otpdata(event){
this.setState({[event.target.name] : event.target.value})
}
onOpenModal = () => {
this.setState({ isOpen: true });
};
onCloseModal = () => {
this.setState({ isOpen: false });
};
otpValidate = (e) => {
alert(this.state.otp);
}
html调用引用
<div className="otp_modal">
<Otp ref={this.otpModalRef } ></Otp>
</div>
请帮助。谢谢。