【问题标题】:Invariant violation: could not find store in either the context or props不变违规:无法在上下文或道具中找到存储
【发布时间】:2019-01-19 01:34:01
【问题描述】:

我在 Login.js 中创建了一个商店,当用户登录时,用户名会发送到商店。然后在 Profile.js 中我得到这个用户名并渲染它。

代码如下所示:

Profile.js

import { connect, Provider } from "react-redux";

function mapStateToProps (state) {
  return {
    user: state.user
  }
}
export class Profil extends React.Component {

  render() {
    return (
      <Provider store={store}>
        <View>
          <Header
            centerComponent={{ text: 'Profil', style: { color: '#FF0000', fontSize: 20, fontWeight: 'bold' } }}
            outerContainerStyles={{ backgroundColor: '#ffffff' }}
          />
          <Text>Willkommen { this.props.user } </Text>
        </View>
      </Provider>
    );
  }
}

export default connect(mapStateToProps)(Profil)

登录.js

body: JSON.stringify({

  email: UserEmail,

  password: UserPassword,

  name: UserName

})

}).then((response) => response.json())
    .then((responseJson) => {

      // If server response message same as Data Matched
     if(responseJson === 'Data Matched')
      {

          //Then open Profile activity and send user email to profile activity.
          this.props.navigation.navigate("Tabs");
          store.dispatch({
            type: 'ADD_USER',
            user: { Name: UserName }
          });

      }
....

var userReducer = function(state, action) {
 if (state === undefined) {
  state = [];
}
 if (action.type === 'ADD_USER') {
  state.push(action.user);
}
return state;
}

export var store = createStore(userReducer);

但是每次运行应用程序时,我都会收到相同的错误:不变违规:在上下文或道具中找不到存储

这里有什么问题?我该如何解决?

【问题讨论】:

  • 我刚才回答了一个类似的问题,你可以关注解决方案here

标签: javascript reactjs react-native redux react-redux


【解决方案1】:

问题存在,因为&lt;Provider store={store}&gt; 应该包装在您的初始应用程序上下文中。 connect() 是不可能的,因为此时商店尚未在您的父应用程序上下文中初始化,并且当状态本身在当前组件中设置时,它正在尝试将您的状态映射到道具。确保 &lt;Provider&gt; 包含在不需要 connect() 的组件中,如下所示:

export var store = createStore(userReducer);

ReactDOM.render(
  <Provider store={store}>
    <MyAppComponent />
  </Provider>,
  document.getElementById('root')
)

此时,connect() 将在您的任何子组件中工作,并将从存储中读取。

【讨论】:

  • 在这种情况下“rootEl”是什么意思?
  • @DrueTrue 我已经更新了。 rootEl 只是您的应用程序安装在您的 DOM 中的位置。初始化商店时:您很快就会将应用程序渲染到实际页面中。此时,您需要获取刚刚初始化的商店,并将其传递给&lt;Provider&gt; 进行初始化(包裹在您的根应用程序组件周围)。
  • 现在我收到:“找不到变量:ReactDOM”。我应该从 react-redux 导入它吗?
  • ReactDOM 是用于将应用实际呈现到浏览器中的反应包。
  • 但是如果我将 React Native 用于移动应用程序,那我该怎么做呢?
猜你喜欢
  • 2018-10-08
  • 2016-07-12
  • 2016-04-30
  • 2023-03-24
  • 2017-12-02
  • 2019-09-13
  • 2017-04-22
  • 2020-05-06
相关资源
最近更新 更多