React-no-redux无法通过react-router传递appstate

时间:2017-12-08 15:22:33

标签: javascript reactjs

我试图使用React-No-Redux,它是redux但没有redux包。我将把我的代码放在下面,因为我遇到的问题是我可以访问路由器外部导航栏中的道具,但我无法从路由器内的任何组件内部访问appState。

AppState.js

import React, { Component } from 'react';

export default class AppState extends Component {
  constructor(props) {
    super(props);
    this.state = {
      test: 'hello im a test string'
    };
    this.setAppState = this.setAppState.bind(this);
}

setAppState(newState, callback) {
  this.setState(newState, callback);
}

render() {
  return (
    <div className="AppState">
    {React.Children.map(this.props.children, child => {
      return React.cloneElement(child, {
      appState: this.state,
      setAppState: this.setAppState
      });
    })}
  </div>
  );
}
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import registerServiceWorker from './registerServiceWorker';

import AppState from './AppState';
import StateConstants from './constants/stateConstants';
import Error404 from './views/errorPages/Error404';

ReactDOM.render(
  <Router>
    <AppState>
      <App
        setAppState={this.setAppState}
        appState={this.appState}
      />
    </AppState>
  </Router>
  , 
  document.getElementById('root')
);
registerServiceWorker();

App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Error404 from './views/errorPages/Error404';
import Home from './views/pages/Home';
import Navbar from './partials/Navbar';

import './App.css';

class App extends Component {
  render() {
    return (
      <div>
        <Navbar 
          setAppState={this.props.setAppState}
          appState={this.props.appState}
        />
        <Switch>
          <Route exact path='/' component={Home} appState={this.props.appState} setAppState={this.props.setAppState} />
          <Route component={Error404} />
        </Switch>
      </div>
    );
  }
}

export default App;

Navbar.js

import React, { Component } from 'react';

export default class Navbar extends Component {
  constructor(props){
    super(props);
    console.log(this.props);
  }

  render(){
    return (
      <div className="navbar"><center><h1>Hello Navbar</h1></center</div>
    );
}
}

Home.js它正在错误的那个说不能读取未定义的属性测试

import React, { Component } from 'react';

export default class Home extends Component{
  constructor(props){
    super(props);
    console.log(this.props);
  }

  render(){
    return (
      <div>
        {this.props.appState.test}
      </div>
    );
  }

}

这应该像我以前做过的那样工作,这与我上次做的完全一样。

1 个答案:

答案 0 :(得分:0)

我的错,唯一我做错的是我把component = {}而不是render = {}

()} /&gt;