我以前在我的顶级React组件Provider
周围包裹了App
上下文。然后,我决定将上下文直接移动到ReactDOM.render
,以便可以在connect
中使用redux App
。我想使用connect
,以便可以将加载程序(LinearProgress
)用作应用程序的顶部组件。因此,我将从道具中导入loading
并相应地显示一个加载程序(可以从某些内部组件中切换loading
。)
但是我仍然收到此错误:
Warning: Cannot update during an existing state transition (such as within
渲染). Render methods should be a pure function of props and state.
该页面仍可正常显示,但控制台中出现上述错误。我检查了导致错误的行是以下行(在App
内部):
{loading && <LinearProgress color='secondary'/>}
如果我删除该行,那么控制台中不会报告任何错误。为什么App
内部有条件地显示加载器会导致错误?
这是App
组件的代码:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import LinearProgress from '@material-ui/core/LinearProgress';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import SearchAppBar from './components/layout/MaterialHeader.js';
import AppInfo from './components/appOperations/AppInfo.js';
import About from './components/layout/About.js';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import constants from './constants';
class App extends Component {
render() {
const { loading } = this.props;
return (
<Router>
<div className="App">
{loading && <LinearProgress color='secondary'/>}
<SearchAppBar/>
<Switch>
<Route exact path="/" />
<Route exact path={constants.CLIENT_ROUTES.APP} component={AppInfo}/>
<Route exact path="/about" component={About}/>
</Switch>
</div>
</Router>
);
}
}
App.propTypes = {
loading: PropTypes.bool.isRequired
};
const mapStateToProps = state => ({
loading: state.app.loading
});
export default connect(mapStateToProps, null)(App);
这是App
的父级和最顶层组件的代码:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider';
import App from './App';
import MaterialBlueTheme from './components/layout/MaterialBlueTheme.js';
import * as serviceWorker from './serviceWorker';
import store from './store.js';
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider theme={MaterialBlueTheme}>
<App />
</MuiThemeProvider>
</Provider>
, document.getElementById('root')
);
serviceWorker.unregister();
答案 0 :(得分:0)
寻找一个试图更改render方法内状态的组件。您不能这样做:
render() {
this.setState({
...
});
return (...);
}