同时使用多个React Provider渲染组件

时间:2019-02-28 15:41:01

标签: reactjs react-redux components

我有两个成分<App/><PitPage/>都相似,并且在其中使用了另一个成分<PitComponents/>。这两个组件都在React提供的<Provider/>下使用,并使用我创建的同一商店。请注意,在调度事件时(在文件vanillaRedux.js内部) <PitComponents uName="Badari Krishna" user={this.props.create.users[0].name}/>中的这一行App.js产生正确的答案输出“ BK”,但我希望类似的情况发生在PitPage.js中,其中显示users是未定义的。请让我知道我要去哪里错了。屏幕截图或结果也将被附加。

index.html(如下)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body>

    <!-- binds App.js code here -->
    <div id="root"></div>


    <!-- binds PitPage code here -->
    <div id="pit"></div>

  </body>
</html>

index.js(如下)

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {Provider} from 'react-redux';
import globalStore from './components/pit/vanillaRedux';


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

serviceWorker.unregister();

enter image description here

App.js(如下)

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import vanillaRedux from './components/pit/vanillaRedux';

import PitComponents from  './components/pit/PitComponents';
import {connect} from 'react-redux';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} class="App-logo" alt="logo" />
          <p>
            Edit <h1>src/App.js</h1> and save to reload.
          </p>
          <a
            class="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
        <PitComponents uName="UserName" user={this.props.create.users[0].name}/>
      </div>
    );
  }
}

const mapStateToProps= (state) =>{

  return {
      create: state.userCreateReducer
  }

};

const mapDispatchToProps= (dispatch) => {
  return {
      setName: () => {
          dispatch({
                  type: "DELETE",
                  id:3
          });
      }
  }
}


export default connect(mapStateToProps,mapDispatchToProps)(App);

PitPage.js(如下)

import React from 'react';
import ReactDOM from 'react-dom';
import PitComponents from  './PitComponents';

import {connect} from 'react-redux';
import {Provider} from 'react-redux';
import globalStore from './vanillaRedux';


class PitPage extends React.Component{


    render(){
        return(
            <PitComponents uName="user" user={this.props.create.users[0].name}/> <!--this is where error is thrown saying "user" undefined -->

        );
    }

}

const mapStateToProps= (state) =>{

    return {
        create: state.userCreateReducer
    }

  };

const mapDispatchToProps= (dispatch) => {
    return {
        setName: () => {
            dispatch({
                    type: "DELETE",
                    id:3
            });
        }
    }
}


ReactDOM.render(<Provider store={globalStore}><PitPage /></Provider> , document.getElementById('pit'));

export default connect(mapStateToProps,mapDispatchToProps) (PitPage);

enter image description here

vanillaRedux.js(如下)

import {createStore, applyMiddleware} from 'redux';
import { combineReducers } from 'redux';
import logger from 'redux-logger';

const usersInitialState = {

    exmple: 'Example',
    users: []
};


const userCreateReducer = (state = usersInitialState,action) =>{


    switch(action.type){

        case "CREATE":
        console.log("CREATE called..!!");
        state = {
            ...state,
            users: [...state.users,action.user]
        };

        break;

    }

    return state;

};

const globalStore = createStore(userCreateReducer,applyMiddleware(logger) );

globalStore.subscribe(() => {
    console.log('globalStore updated -->',globalStore.getState());
});

globalStore.dispatch({

    type: "CREATE",
    user: {  
        id: 1,
        name: 'BK',
        age: 23,
        }
});

PitComponents.js(如下)

import React from 'react';

class PitComponents extends React.Component{

    constructor(props){
        super(props);
      }

    render(){
        return(
            <div>
                <h1> Welcome {this.props.name} </h1>
                <p> This is PIT 1 </p>
                <p> From Redux --> {this.props.user} </p>
            </div>

        );
    }

}


export default PitComponents;

1 个答案:

答案 0 :(得分:0)

我做了一些调整,以使我可以解决这个问题,但是我却能正常工作。

我要做的主要事情是重组mapStateToProps以将用户映射到状态。

无论如何,我希望这对您有所帮助-代码位于:

https://codesandbox.io/embed/v6x49617z5?fontsize=14