React 将 prop 传递给组件返回 undefined

tom*_*son 8 javascript reactjs react-router

我真的很困惑为什么当我路由到我的项目的http://localhost:3000/subjects/physics时。

变量gradeSelection 在App.js 状态中定义。它通过 props 作为gradeSelection 传递给subjectCards.js 组件,后者通过props 作为gradeSelection 将它传递给Subject.js 组件。

然而,Subjects.js 中的 this.props.gradeSelection 返回 undefined。

我可能做错了什么吗?

控制台输出:

App.js: Year 12             // correct
subjectCards.js: Year 12    // correct
Subject.js: undefined       // not correct
Run Code Online (Sandbox Code Playgroud)

应用程序.js

constructor(props) {
  super(props);
  this.state = {
    gradeSelection: "Year 12"
  };
}

render() {
  console.log("App: "+this.state.gradeSelection)
  return (
    <Route path="/subjects" render={(props)=>(<SubjectCards {...props}  gradeSelection={this.state.gradeSelection} />)} />
);


}
Run Code Online (Sandbox Code Playgroud)

主题卡片.js

let display;

console.log("subjectCards.js: "+props.gradeSelection)
display = <Route path="/subjects/:subjectName" render={(props)=><Subject {...props} gradeSelection={props.gradeSelection}/>} />


return (
  display
);
Run Code Online (Sandbox Code Playgroud)

主题.js

constructor(props) {
  super(props);
  console.log("Subject.js: "+this.props.gradeSelection);  // undefined
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑:

当 Subjects.js 构造函数中的 console.log(props) 或 console.log(this.props) 时。控制台输出中的 gradeSelection 仍然未定义..

我试过将一个字符串传递给 subjectCards.js 中的 gradeSelection 并且控制台输出在返回 Subject.js 中的字符串时是正确的。

display = <Route path="/subjects/:subjectName" render={(props)=><Subject {...props} gradeSelection={"props.gradeSelection"}/>} />
Run Code Online (Sandbox Code Playgroud)

Den*_*nez 5

在没有看到您的其余代码的情况下,我将假设 subjectCards.js 是一个看起来像这样的功能组件。如果不是,您能否发布完整的组件?

function SubjectCards(props) {
  let display

  console.log('subjectCards.js: ' + props.gradeSelection)

  display = (
    <Route
      path="/subjects/:subjectName"
      render={props => (
        <Subject {...props} gradeSelection={props.gradeSelection} />
      )}
    />
  )

  return display
}
Run Code Online (Sandbox Code Playgroud)

我在您的特定用例中看到的这段代码的错误在于,在第 1 行,您有一个名为props. 如果您按照代码向下到第 9 行,您会注意到内部的匿名函数调用render也有一个props参数。在第 10 行,您正在调用props.gradeSelectionwhich 将查看第 9 行中找到的参数而不是第 1 行中找到的参数,从而为您提供 undefined。

有几种不同的方法可以解决这个问题。我推荐的一种方法是解构props在第 1 行的论点。

function SubjectCards({ gradeSelection }) { // See how we went from props to {gradeSelection}
  let display

  console.log('subjectCards.js: ' + gradeSelection)

  display = (
    <Route
      path="/subjects/:subjectName"
      render={props => <Subject {...props} gradeSelection={gradeSelection} />}
    />
  )

  return display
}
Run Code Online (Sandbox Code Playgroud)

你可以在https://mo9jook5y.codesandbox.io/subjects/math 上看到一个例子

你可以在这里玩这个例子:https : //codesandbox.io/s/mo9jook5y