【问题标题】:React/Redux: Where are my props?React/Redux:我的道具在哪里?
【发布时间】:2018-08-09 17:18:12
【问题描述】:

这是我第一次用这个堆栈组合一个新的应用程序。以前,我在另一个已经安装了管道的演出中工作了一个继承的。我的道具未定义,我需要知道原因。也请提出建议。这是删减的代码:

index.js

const store = createStore(rootReducer);
render(<Root store={store} />, document.getElementById("root"));

Root.js

const Root = ({ store }) => (
  <Provider store={store}>
    <Router>
      <Route path="/:filter?" component={App} />
    </Router>
  </Provider>
);
Root.propTypes = {
  store: PropTypes.object.isRequired
};
export default Root;

App.js

const App = ({ classes }) => ( // SHOULDN'T THIS BE DESTRUCTURED FROM PROPS?
  <div className={classes.root}> // <== UNDEFINED...WHY NO PROPS?
    <Grid container spacing={24}>
      <Grid item xs={12}>
        <AppBar />
      </Grid>     
    </Grid>
  </div>
);

export default withRoot(compose(connect())(App));

withRoot.js (从 Material-UI 创建一个默认主题)

const theme = createMuiTheme({
  palette: {
    type: "dark"
  },
  typography: {
    fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
    fontSize: 14,
    fontWeightLight: 300,
    fontWeightRegular: 400,
    fontWeightMedium: 500
  }
});

function withRoot(Component) {
  function WithRoot(props) {
    // MuiThemeProvider makes the theme available down the React tree
    // thanks to React context.
    return (
      <MuiThemeProvider theme={theme}>
        {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
        <CssBaseline />
        <Component {...props} />
      </MuiThemeProvider>
    );
  }

  return WithRoot;
}

export default withRoot;

【问题讨论】:

  • 连接中没有 mapStateToProps - 您应该通过部分存储

标签: javascript reactjs redux react-redux material-ui


【解决方案1】:

您需要传递connect 一个将您的状态映射到道具的函数

const mapStateToProps = (state) => ({
  classes: state.classes
});

export default withRoot(compose(connect(mapStateToProps))(App));

【讨论】:

  • 我忘了补充说我正在使用 Material-UI。此外,上游的非 SFC 组件父亲可以通过 this.props 获得他们的道具。我更新了我的帖子。你的回答还适用吗?
  • 如果 props 正在进入 App.js,那么应该从 props 中解构类(假设它们处于状态)。对?然而,道具是未定义的。
  • 您正在将您的 App 组件连接到商店,但我认为您可能需要将更高阶的 withRoot 组件连接到商店。目前,WithRoot 没有可使用的上下文。 connect()(withRoot(App))
  • 你是这个意思吗? “用Root(App)导出默认值;”和“导出默认 compose(connect())(withRoot);”这给了我虚假的“TypeError:无法将类作为函数调用”。
【解决方案2】:

您可能正在寻找作为道具传递的theme 对象。 Material-UI 使用上下文 api,而不是 redux。

withTheme()(组件) => 组件

提供主题对象作为输入组件的属性。

【讨论】:

  • 这行不是已经在 withRoot 中处理好了:??
  • 它不是提供者部分(一个为所有) - 不是上下文“消费者”(对于需要它的组件)?
  • 对不起,我不明白你的问题。
  • 在创建上下文的地方连接上下文有点棘手。如果您要在 AppBar 中使用主题,那么您将使用 withTheme()(AppBar)consume theme context。当你需要它'root'时,你可能需要withRoot(withTheme()(App)) 或在redux 连接旁边的compose 中使用withTheme。 stackoverflow.com/questions/51265319/…
  • 我在 App.js 的 compose() 和“withRoot(withTheme()(App))”中添加了 withTheme() - 不走运。这是你建议的吗?
猜你喜欢
  • 1970-01-01
  • 2018-06-19
  • 2016-08-15
  • 2018-09-12
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
相关资源
最近更新 更多