我有一个问题,用setState函数,这是问题:
警告:setState(...):只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了setState()。这是无人值守。请检查登录组件的代码。
我不知道为什么会这样,这是代码:
LogIn.js(初始页);
import React, { Component } from 'react';
import firebase from 'firebase';
import { Redirect } from 'react-router-dom';
export default class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
loggedIn : false
};
}
handleAuth(){
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
let auth = firebase.auth();
let promise = auth.signInWithEmailAndPassword(email, password);
promise.then(result=>{
console.log(result.email);
});
promise.catch(error=> {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
alert(errorMessage);
});
}
componentDidMount(){
firebase.auth().onAuthStateChanged(firebaseUser =>{
console.log(firebaseUser.email);
if (firebaseUser.email) {
this.setState({
loggedIn: true
});
}
else{
alert("No logeado");
}
});
}
render(){
if (this.state.loggedIn) {
return ( <Redirect to="/Dashboard"/> );
}
return(
<div className="container comunidadLogIn">
<div className="row" >
<div className="col-sm-2 push-5 align-self-center" >
<input type="text" name="email" id="email" placeholder="Email"/>
</div>
</div>
<div className="row" >
<div className="col-sm-2 push-5 align-self-center" >
<input type="password" name="password" id="password" placeholder="Password"/>
</div>
</div>
<div className="row" >
<div className="col-sm-2 push-5 align-self-center" >
<button className="btn btn-secondary" onClick={this.handleAuth} id="btnLogin">Iniciar sesión</button>
</div>
</div>
</div>
);
}
}
Dashboard.js(登录为true时重定向此页面);
import React, { Component } from 'react';
import Header from '../../components/Template/Header/Header.js';
import PanelUsers from '../../components/Template/Users/PanelUsers.js';
import CardGroup from '../../components/Dashboard/Cards/CardGroup.js';
import CardDecks from '../../components/Dashboard/DetailCard/CardDecks.js';
import store from '../../store';
import { Dashboard } from '../../db';
export default class LogIn extends Component {
constructor() {
Dashboard();
super();
this.state = {
dataState: []
};
}
componentDidMount(){
store.subscribe(()=>{
this.setState({
dataState: store.getState().dataDashboardReducer.data
});
});
}
componentWillUnmount(){
console.log("componente desmontado Dashboard");
}
render(){
return(
<div>
<Header />
<div className="row">
<div className="col-sm-2">
<PanelUsers/>
</div>
<div className="col-sm-6" >
<CardGroup datos= { this.state.dataState }/>
</div>
<div className="col-sm-4">
<CardDecks/>
</div>
</div>
</div>
);
}
}
当我转到另一个页面并返回登录时,它发生了
最佳答案
发生这种情况是因为您试图在componentWillMount()中设置状态,而尚未安装组件。将其更改为componentDidMount(),它应该可以正常工作。