【发布时间】:2016-12-27 16:12:03
【问题描述】:
我正在用 react 编写代码,我刚开始使用 redux(因为我需要一个容器)。但是,我现在已经被困在一个地方了。
我收到此错误 -
不变违规:在上下文中找不到“商店”或 “连接(主页)”的道具。要么将根组件包装在 , 或明确地将“商店”作为道具传递给 “连接(主页)”。
我试过谷歌搜索,根据 react-redux 的troubleshooting section,可以使用这三个东西来检查:
1. 确保页面上没有重复的 React 实例。
2. 确保您没有忘记将根组件包装在
3. 确保您运行的是最新版本的 React 和 React Redux。
我有以下代码是根(这是使用提供程序定义商店的地方) -
import React from 'react';
import { Router, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';
import routes from '../Routes';
import reducers from './reducers/reducers';
import actions from './actions/actions';
export default class AppRoutes extends React.Component {
render() {
const store = createStore(reducers, applyMiddleware(reduxThunk));
return (
<Provider store={store}>
<Router history={browserHistory} routes={routes} onUpdate={() => window.scrollTo(0, 0)}/>
</Provider>
);
}
}
而且这个错误只发生在我拥有的两个组件之一上 -
// No error when connected only in this component
import React from 'react';
import { connect } from 'react-redux';
import * as actions from './actions/actions';
class Dashboard extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h1>Hello, {this.props.isAuthenticated.toString()}</h1>;
}
}
function mapStateToProps(state) {
return {
content: state.auth.content,
isAuthenticated: state.auth.authenticated
};
}
export default connect(mapStateToProps, actions)(Dashboard);
// Error thrown when I try to connect this component
import React from 'react';
import LoginPage from './LoginPage';
import Dashboard from './Dashboard';
import Loading from './Loading';
import { connect } from 'react-redux';
import * as actions from './actions/actions';
class HomePage extends React.Component {
constructor(props) {
super(props);
this.setState({
loading: true
});
}
render() {
var inPage = undefined;
if(this.props.isAuthenticated) {
console.log('Logged in');
inPage = <Dashboard user = {HomePage.user}/>;
}
else if (this.state.loading){
console.log('Loading');
inPage = <Loading />;
}
else {
console.log('Login');
inPage = <LoginPage />;
}
return (
<div>
{inPage}
</div>
);
}
}
function mapStateToProps(state) {
this.setState({
loading: false
});
return {
content: state.auth.content,
isAuthenticated: state.auth.authenticated
}
}
export default connect(mapStateToProps, actions)(HomePage);
【问题讨论】:
-
我认为您不应该在 mapStateToProps 中执行 setState,此时您不在反应组件上下文中。另外,我认为您的 AppRoutes 组件是错误的,我通常从组件/路由声明中创建商店和所有与 redux 相关的变量。
-
@JeremyD 我删除了 setState,并切换到您正在谈论的设置(将所有基于 redux 的东西移到外面)。但它仍在发生。我一直在努力弄清楚如何让它发挥作用。
标签: javascript reactjs redux react-redux