在 "Connect(MyComponent)" 的上下文中找不到 "store"。要么将根组件包装在 <Provider> 中,

Could not find "store" in the context of "Connect(MyComponent)". Either wrap the root component in a <Provider>,

我正在为我的 Web 应用程序设置 React-Redux,我在 "Connect(Register)" 的上下文中遇到无法找到 "store"。

我想也许我必须通过我在 [[2]] store.js 中创建的商店并且它有效但我没有在网上看到它以这种方式完成,当我尝试使用 redux DevTools 时它一直显示找不到商店。

我认为 connect() 的目的是环绕组件并通过 mapStateToProps 访问 redux 中的全局状态。如果有人可以指出正确的方向或者可能解释为什么我会收到此错误,那就太好了!

我尝试过的东西:

  1. 因为我有一个容器组件 LoginContainer.js(我可以通过 connect()(LoginContainer) 访问它,我想我可以在这里访问状态并将道具传递给register.js 组件,然后向上传播状态更改。

  2. 我一直在考虑将 register.js 更改为功能组件,因为这可能会以某种方式影响它?

我一直在阅读上下文以及如何通过在 index.js 处使用 <Provider store={store}> 它应该允许通过 connect(mapState,MapDispach)(Component) 访问 Redux 存储但是我仍然不能区分我是如何或何时失去提供者的背景。

//index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux"
import { BrowserRouter, Route } from "react-router-dom";
import store from "./store";

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <App />
    </Provider>
  </BrowserRouter>,
  document.getElementById("root")
);

// App.js 

import React, { Component } from "react";
import {
  Route,
  Switch
} from "react-router-dom";
import LoginContainer from "./containers/login";
class App extends Component{
  render() {
    return (
          <div className="App">
          <header className="App-header">
          <Switch>
          <Route path='/login' component={LoginContainer} />
          </Switch>
          </header>
          </div>

    );
  }
}

export default App;


// LoginContainer.js 
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Register from "../componets/Registration/register";
import Login from "../componets/Login/login";
import { withRouter } from "react-router-dom";
import { Input, Button } from "semantic-ui-react";
import { connect } from "react-redux";
import store from "../store";
class LoginContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
        //some local UI states
    };
  }
  render() {
    return (
      <div>
        <div className="ToggleContainer">
          <div className={"toggle"}>
            <Button.Group>
              <Button
                onClick={this.registerHandler}
                positive={this.state.registerOn}
              >
                SignUp
              </Button>
              <Button.Or />
              <Button onClick={this.loginHandler} positive={this.state.loginOn}>
                Login
              </Button>
            </Button.Group>
          </div>
 <Provider store = {store}> <Register {...this.props} /> </Provider> // [[6]], uncommented [[4]] works but is it different than method [[1]]?
 //  <Register{...this.props} /> // [[2]] cannot connect to store
       // <Register store={store} {...this.props} />} [[1]] can connect store via directly sending store //
        </div>
      </div>
    );
  }
}



  // ReactDOM.render(<LoginContainer />,  document.getElementById("root")); [[answer]] removing this fixed the problem

const mapStateToProps = state => {
  return {
    loggedIn: state.registration.isLoggedIn
  };
};

const mapDisptachToProps = dispatch => ({
  registerUser: id => dispatch({ type: "SIGN_IN" })
});
export default withRouter(
  connect(
    mapStateToProps,
    mapDisptachToProps
  )(LoginContainer)
);



//components/register.js

import React, { Component } from "react";
import { Input, Button } from "semantic-ui-react";

import { connect } from "react-redux";

class Register extends Component {
  constructor(props) {
    super(props);
    // Local State

  }
   const check() {
   let userData: User;
    if (validEmail(this.state.email)) {
      userData = {
       //data 
      };

     let user = await this.handleSignUp(userData);
       const res = JSON.parse(user);

        if (res.message === "Success") {
          alert('Account success')
        }
      if(typeof user === 'string'){
         user =JSON.parse(user)
      }
    } else {
      this.setState({ hiddenErrorMessage: false });
    }
    this.props.registerUser(userData);

    // func: returns true if it is valid, o.w. false
    function validEmail(email) {

    }
  };
  //handlers()

  render() {
    return (
      // eslint-disable-next-line react/jsx-filename-extension
      <div>
        <Input
          className="customInput"
          onChange={this.handleEmail}
          placeholder="Email"
        />
        <Input
          className="customInput"
          onChange={this.handlePassword}
          placeholder="Password"
          type="password"
        />
        <br />
        <Button
          size="big"
          className="customButton"
          onClick={this.checkUserInput}
        >
          Sign up
        </Button>
        <p>
          <span hidden={this.state.hiddenErrorMessage}>
            Invalid Email/Passoword
          </span>
        </p>
      </div>
    );
  }
}

const mapStateToProps = (state) => {

 return {
   loggedIn:state.registration.isLoggedIn
 }
};

const mapDisptachToProps = dispatch => ({
  registerUser: id =>  dispatch({ type: "SIGN_IN" }) // return dispatch
});

export default Register // [[3]] Works as expected
// export default connect( [[4]] Could not find "store" in the context of "Connect(Register)". Either wrap the root component in a <Provider> Error
//   mapStateToProps,
//   mapDisptachToProps
// )(Register);


//store.js 

import { createStore } from "redux";
import rootReducer from './reducers';

export default createStore(rootReducer);


//reducers/index.js

import { combineReducers } from "redux";
import registration from "./registration";

export default combineReducers({ registration });

//actionType.js
const SIGN_IN = 'SIGN_IN';

export { SIGN_IN };
//reducers/registration.js

const initialState = {
  isAuthenticated: false,
  isLoggedIn: false,
  isLoggedOut: false,
  userId : ''
};

export default (state = initialState, action) => {
  if (action.type === "SIGN_IN") {
    return { ...state, isLoggedIn: true };
  }
  if (action.type === "SIGN_OUT") {
    return { ...state, isLoggedOut: true };
  }
  return state;
};

此问题的解决方案是从 LogainContainer 中删除下一个代码:

ReactDOM.render(<LoginContainer />,  document.getElementById("root"));