【问题标题】:how to read state in the main component App, it's seems is not created如何在主组件App中读取状态,似乎没有创建
【发布时间】:2017-10-06 08:56:14
【问题描述】:

我有一个简单的reducer,它只定义了一个默认变量'theme',除了返回这个值什么都不做:

appreduce.js

const initialState = {
  theme: 'skyhola',
};

export default (state = initialState, action) => {
  switch (action.type) {
    default:
      return state;
  }
};

在不是主 App.js 的组件上,我可以读取到这个状态:

import  React, { Component } from 'react';
import { connect } from 'react-redux';
class TestColors extends Component {
  render() {
    return (
      <div>
         Theme: { this.props.theme }  // <---it's ok, print 'sky'
      </div>
    );
  }
}

export default connect(
  (state) => ({ theme: state.app.theme }),
)(TestColors );

但是如何在主要组件上阅读它?因为我需要在渲染中写:

<ThemeProvider theme={ HERE MY STATE THEME !! }>

状态正在创建过程中,console.log 正在渲染中,或者 ComponentDidMount 给我空 {},我无法使用来自 redux 的 'connect' 来写入 App,因为它正在创建应用程序...

app.js

const store = createStore(
  combineReducers({
    apollo: client.reducer(),
    app: appReducer,
  }),
  {},
  compose(
    applyMiddleware(client.middleware()),
    // If you are using the devToolsExtension, you can add it here also
    window.devToolsExtension ? window.devToolsExtension() : f => f,
  ),
);

class App extends Component {

  componentDidMount () {
    console.log(this.props);  <--- nothing here, how to read the state?
  }
  render() {

    return (
      <ApolloProvider store={store} client={client}>
        <BrowserRouter>
          <ThemeProvider theme={ HERE MY STATE THEME !! }>

              <Switch>
                <Route exact path="/signin" component={SignInPage} />
              </Switch>


          </ThemeProvider>
        </BrowserRouter>
      </ApolloProvider>
    );
  }
}

export default App;

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    要读取这种情况下的状态,您需要调用 store 的 getState 方法。

    class App extends Component {
      componentDidMount () {
      console.log(store.getState()); // current state of the application
      // Prints: app: {theme: "skyhola"}
    }
    

    您可以查看this fiddle

    【讨论】:

      【解决方案2】:

      你的 mapStateToProps 应该是 state.theme 而不是 state.app.theme

      export default connect(
        (state) => ({ theme: state.theme }),
      )(TestColors );
      

      你需要调用App组件的构造函数。

      class App extends Component {
        constructor(props){
          super(props)
        }
        ...
      }
      

      【讨论】:

      • 我不认为。 props 在那里未定义,我需要在
      • 谢谢,但我认为你不明白这个问题,有 combineReducers,所以 state.app.theme 没问题,并且在该组件工作时,问题出在 app.js
      猜你喜欢
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      相关资源
      最近更新 更多