gpt4 book ai didi

javascript - 如何从具有 `connect` 上下文的同一组件调用 `Provider` 以导入 redux 状态?

转载 作者:行者123 更新时间:2023-11-30 06:20:18 25 4
gpt4 key购买 nike

我曾经有Provider围绕我的顶级 React 组件的上下文:App .然后我决定将上下文直接移动到 ReactDOM.render这样我就可以使用 redux connectApp .我想用 connect这样我就可以使用加载器 ( LinearProgress ) 作为我应用程序中的顶级组件。所以我将导入 loading从 props 并相应地显示一个加载器(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();

最佳答案

寻找试图在渲染方法中更改状态的组件之一。你不能这样做:

render() {
this.setState({
...
});

return (...);
}

关于javascript - 如何从具有 `connect` 上下文的同一组件调用 `Provider` 以导入 redux 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53565001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com