【问题标题】:React.js : Passing Props from a Function to a ComponentReact.js:将道具从函数传递到组件
【发布时间】:2018-02-19 19:22:38
【问题描述】:

我正在尝试让 App(组件)调用 Main(函数),而 Main(函数)又调用 Leads(组件),我希望道具跟随。 Main 是为我的应用返回所有路由的函数。我正在使用 React Router v4。

我已经尽可能地简化了下面的代码,希望不会太多:

App 调用 Main 并传递 props:leads & library。

App.js

class App extends Component {
  render() {

    return (
      <div>
        <nav>
          <Link to="/library">Library</Link>
          <Link to="/leads">Leads</Link>
        </nav>
        <Main 
          leads={this.state.leads}
          library={this.state.library}
        />
      </div>
    );
  }
}

export default App;

这里有道具,没问题。然而,我的理解是 props 是函数 Main 的局部变量,因此指向它是问题,因为一旦函数运行,props 就会被破坏。

Main.js (简体)

    const Main = (props) => (

    <main>
        <Switch>
            <Route exact path="/leads" render={(props) => (
                <Lead
                    {...props}
                    leads={props.leads}
                /> )}
            />
        </Switch>
    </main>
)

export default Main;

这里,Leads.js 中的 this.props.leads 指向 null 并且 {Object.keys(this.props.leads)} 失败。 (为简单起见,我删除了 renderLeads() 的代码)

Leads.js (简化版)

class Lead extends React.Component {

    render() {

        return (
            <div>
                <h2>Leads</h2>
                <table>
                    <tbody>
                        {Object.keys(
                            this.props.leads).map(
                            this.renderLeads)}
                    </tbody>
                </table>
            </div>
        );
    }
}


export default Lead;

我已经通过将 Main 设置为 React.Component 的扩展类来“解决”这个问题。我仍然觉得 Main 应该是一个函数,它只处理数据而不保存自己的数据......

  1. Main 应该是一个函数吗?
  2. 我对情况的评估准确吗?
  3. 将道具从 Main 传递到 Leads 的正确方法是什么?

提前致谢。

【问题讨论】:

    标签: javascript reactjs ecmascript-6 react-router


    【解决方案1】:

    当您在内部范围内声明一个与位于上层范围内的另一个变量(在本例中为变量“props”)同名的变量时,您的错误就是“变量阴影”。

    在 Main.js 中,您正在渲染 &lt;Lead /&gt;,将功能组件传递给路由,传递路由器提供给您的 props,而不是您在渲染 &lt;Main /&gt; 时传递的那个应用.js。

    我知道这有点令人困惑,但这解释了为什么当您将 Main 更改为 Class 组件时它会起作用,您可能使用this.props 调用,对吧?所以在这种情况下,你叫对了。

    您可以决定&lt;Main /&gt; 应该是函数式组件还是类,但通常没有状态的组件应该是函数式的。您可以简单地在外部范围(主要)或内部(路线)中更改道具的名称。示例:

    <Route exact path="/leads" render={(routerProps) => (
            <Lead
                {...routerProps}
               leads={props.leads}
            /> )}
        />
    

    现在,我们在线索中传递了正确的道具。

    【讨论】:

    • 这完全有道理,现在我看起来很明显。不知何故,我认为这些是相同的道具,但这是错误的,因为 routerProps 将是历史、位置、匹配...谢谢您的帮助!
    猜你喜欢
    • 2021-11-25
    • 2017-10-03
    • 2022-07-19
    • 2019-10-16
    • 2019-01-04
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多