首页 > 解决方案 > 应用组件正在神奇地获取道具?

问题描述

我正在检查一个正常运行的反应网络应用程序的代码库,并努力从 App.js 文件中理解以下内容:

class App extends React.Component {
  render() {
    let error = null
    if (this.props.error) {
      error = <ErrorMessage
        message={this.props.error.message}
        debug={this.props.error.debug} />
    }
    return (
      <Router>
        {this.props.isAuthenticated ?
        <div className="holder">
          <NavBar
            isAuthenticated={this.props.isAuthenticated}
...

具体来说,props(this.props.error 和 this.props.isAuthenticated)从何而来?似乎它没有在任何地方定义。在 Index.js 中,它渲染 App 组件而不传递任何 props ReactDOM.render(<App />, document.getElementById('root'));

编辑:在 App.js 的底部,它被导出,export default withAuthProvider(App) 并且有一个名为 AuthProvider.tsx 的文件定义了errorisAuthenticated

标签: reactjs

解决方案


WellwithAuthProvider是一个高阶组件。您可以在此处了解有关此模式的更多信息。它们实际上是将 React 组件作为参数(App在本例中)并使用道具或逻辑增强它的函数。withAuthProvider包装App组件并为其提供errorisAuthenticated道具,同时它还可以为您实现一些身份验证逻辑。


推荐阅读