我在前端使用 react 和 react 钩子(Hook),我收到了这个错误:
index.js:1 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
in Login (created by Context.Consumer)
in Route (at App.js:46)
in AuthContextProvider (at App.js:37)
in Switch (at App.js:36)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:32)
in div (at App.js:30)
in App (at src/index.js:9)
in StrictMode (at src/index.js:8)
console.<computed> @ index.js:1
overrideMethod @ react_devtools_backend.js:2273
printWarning @ react-dom.development.js:88
error @ react-dom.development.js:60
warnAboutRenderPhaseUpdatesInDEV @ react-dom.development.js:23250
scheduleUpdateOnFiber @ react-dom.development.js:21165
enqueueSetState @ react-dom.development.js:12639
push../node_modules/react/cjs/react.development.js.Component.setState @ react.development.js:471
(anonymous) @ Router.js:34
listener @ history.js:155
(anonymous) @ history.js:173
notifyListeners @ history.js:172
setState @ history.js:288
(anonymous) @ history.js:369
confirmTransitionTo @ history.js:145
push @ history.js:350
Login @ Login.js:66
renderWithHooks @ react-dom.development.js:14803
mountIndeterminateComponent @ react-dom.development.js:17482
beginWork @ react-dom.development.js:18596
beginWork$1 @ react-dom.development.js:23179
performUnitOfWork @ react-dom.development.js:22154
workLoopSync @ react-dom.development.js:22130
performSyncWorkOnRoot @ react-dom.development.js:21756
(anonymous) @ react-dom.development.js:11089
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
flushSyncCallbackQueueImpl @ react-dom.development.js:11084
flushSyncCallbackQueue @ react-dom.development.js:11072
discreteUpdates$1 @ react-dom.development.js:21893
discreteUpdates @ react-dom.development.js:806
dispatchDiscreteEvent @ react-dom.development.js:4168
Show 2 more frames from Library code
登录.js:
import React ,{useState, useContext}from 'react';
import {useHistory} from 'react-router-dom'
import axios from 'axios'
import '../CSS/Ninety.css'
import { AuthContext } from '../../contexts/AuthContext';
const Login = () => {
const history=useHistory()
const {authLog,dispatch} = useContext(AuthContext)
const [Login,setLogin] = useState({
email:'',
password:'',
})
const [response, setResponse] = useState({
email: '',
password: ''
});
const handleSubmit=(e)=>{
e.preventDefault()
axios.post('http://localhost:2000/apiEndpoint/CREATE/user/login', {
email:Login.email,
password:Login.password
},{withCredentials:true},{
headers: {
'Content-Type': 'application/json'
}
})
.then(function (res) {
if(res.data.token){
console.log('SUCCESS', res.data)
dispatch({type: 'LOGIN', payload: res.data});
history.push('/blog')
}else{
console.log('ERRORS',res.data)
setResponse({...response, email: res.data.email, password: res.data.password})
}
})
setResponse({...response, email: '', password: ''})
}
const handleChange=(e)=>{
const {name,value}=e.target
setLogin({ ...Login, [name]: value });
}
console.log('AUTH LOG',authLog)
if(authLog.isAuthenticated){
console.log('You are authenticated and are being redirected to blog')
history.push('/blog');
return null
}else{
return(
<div className='ninetyPer'>
<form onSubmit={handleSubmit}>
<h1>Login up:</h1>
<label name='email'>email:</label>
<input name='email' onChange={handleChange} value={Login.email}></input>
<h5>{response.email}</h5>
<label name='password'>password:</label>
<input name='password' onChange={handleChange} value={Login.password}></input>
<h5>{response.password}</h5>
<button>Submit</button>
</form>
</div>
)
}
};
export default Login;
该错误与 Login.js 中的此有关
....
if(authLog.isAuthenticated){
console.log('You are authenticated and are being redirected to blog')
history.push('/blog');
return null
}else{
....
应用.js:
import React, { Component } from 'react';
import CreateArticle from './components/Pages/CreateArticle'
import Blog from './components/Pages/Blog'
import Navbar from './components/Navbar.js';
import ApiReceiver from './components/new.component'
import {BrowserRouter as Router, Route, Switch, withRouter, Link} from 'react-router-dom'
import Home from './components/Pages/Home'
import About from './components/Pages/About'
import Contact from './components/Pages/Contact'
import Singup from './components/Pages/Signup'
import Login from './components/Pages/Login'
import AuthContextProvider from './contexts/AuthContext';
class App extends React.Component{
constructor(props){
super(props);
this.state= {
posts:[
]
}}
render() {
return (
<div className="App">
<Router>
<Navbar />
<Switch>
<AuthContextProvider>
<Route path="/" exact component={Home} />
<Route path="/blog/create" exact component={CreateArticle} />
<Route path="/blog" component={Blog} />
<Route path="/user/signup" component={Singup} />
<Route exact path="/user/login" component={Login} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</AuthContextProvider>
</Switch>
</Router>
</div>
);
}
}
export default App;
索引.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
如果我的登录已通过身份验证,我正在使用 history.push 重定向到另一个页面。
尽管出现错误,该网站仍在运行,但我有这个警告错误。
最佳答案
那history.push()
将在 render
中引入副作用方法。在这种情况下,它将使 React Router 尝试开始更新 props 以反射(reflect)新路径,这会触发您看到的错误。
而不是使用 history.push()
, 使用 <Redirect />
来自 react-router-dom
的组件反而:
if(authLog.isAuthenticated){
console.log('You are authenticated and are being redirected to blog')
return <Redirect push to="/blog" />
}
通过渲染 Redirect 组件,重定向发生在组件完成渲染之后,这意味着 React Router 所做的更新不会发生在渲染中间。编辑:正如@TimIles 的评论中提到的,添加
push
Prop 将使<Redirect>
充当history.push()
而不是 history.replace()
.
关于javascript - 在现有状态转换期间无法更新(例如在 `render` 内)。渲染方法应该是 props 和 state 的纯函数。在 Index.js 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64306989/