如果用户未登录,我想设置登录用户的状态,然后使用this.setstate()方法将导航设置为true。但是问题在于它在控制台上显示错误并且在这里无法正常运行该程序是错误的
0.chunk.js:219252 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
in Header (at App.js:9)
in App (at src/index.js:17)
in ErrorBoundary (at src/index.js:16)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:15)
以下是我的app.js代码
import React from 'react';
import './App.scss';
import Header from './components/Header/Header';
import Sidebar from './components/Sidebar/Sidebar';
import Routes from './routes/Routes';
function App() {
return (
<>
<Header />
<Sidebar />
<Routes />
</>
);
}
export default App;
Signin.js代码
export default class SignIn extends Component {
constructor(props) {
super(props)
this.state = {
redirect: false,
};
}
}
render() {
if (this.state.redirect) {
return <Redirect to="/" />;
}
}
onSignInHandler = () => {
.......
this.setState({
....
redirect: true,
});
}
在Header.js中具有注销按钮的位置。我想给这个链接onclick()处理程序。下面是代码
export default class Header extends Component {
constructor(props) {
super(props);
this.state = {
navigate: false
}
}
onLogoutHandler = () => {
....
this.setState({
navigate: true,
});
};
render() {
const { navigate } = this.state;
if (navigate) {
return <Redirect to="/signin" push={true} />;
}
return(<header></header>)
}
}
在header.js中,我具有注销链接,该链接将触发onLogoutHandler,然后状态将重定向到登录页面。请帮我解决这个问题
答案 0 :(得分:0)
请检查是否可行
onLogoutHandler = async () => {
....
await this.setState({
navigate: true,
});
};
答案 1 :(得分:0)
您应该在类组件的return
方法末尾有render()
语句
render() {
const { navigate } = this.state;
if (navigate) {
return <Redirect to="/signin" push={true} />;
}
// you should also have return statement in this line here
// return something like
return null;
}