传递道具到组件的React返回未定义

时间:2018-11-22 02:08:16

标签: 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返回未定义。

我可能做错了什么吗?

控制台输出:

App.js: Year 12             // correct
subjectCards.js: Year 12    // correct
Subject.js: undefined       // not correct

App.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} />)} />
);


}

subjectCards.js

let display;

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


return (
  display
);

Subject.js

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

谢谢!

编辑:

在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"}/>} />

3 个答案:

答案 0 :(得分:1)

在没有看到您的其余代码的情况下,我将假定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
}

在您的特定用例中,我在此代码上看到的错误是在第1行上,您有一个名为props的参数。如果您遵循第9行的代码,您会注意到render内部的匿名函数调用也有一个props参数。在第10行上,您正在调用props.gradeSelection,它将在第9行中找到的参数内,而不是在第1行中找到的参数内,从而使您不确定。

有几种解决方法。我建议的一种方法是在第1行上destructuring个参数props

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
}

您可以在https://mo9jook5y.codesandbox.io/subjects/math

上看到一个示例。

您可以在此处使用示例:https://codesandbox.io/s/mo9jook5y

答案 1 :(得分:0)

正如兰迪·卡斯本(Randy Casburn)在评论中所说,您的引用应该是props.gradeSelection,而不是this.props.gradeSelection

道具是作为构造函数(即constructor(props))的输入接收的,因此应这样引用。如果需要在呈现或本地管理它之前进行操作,则可以将其传递给构造函数中Subject的状态。

答案 2 :(得分:0)

您可以这样使用:

//subjectCards.js
render={({gradeSelection, ...other}) => <Subject {...other} 
      gradeSelection={gradeSelection}/>}

//Subject.js
console.log(props.gradeSelection)

但是等等,您只需传递道具即可,它具有您所需的一切(包括gradeSelection):

//subjectCards.js
render={(props) => <Subject {...props} />}

//Subject.js
console.log(props.gradeSelection)