小编tom*_*son的帖子

React 将 prop 传递给组件返回 undefined

我真的很困惑为什么当我路由到我的项目的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 …

javascript reactjs react-router

8
推荐指数
1
解决办法
7891
查看次数

标签 统计

javascript ×1

react-router ×1

reactjs ×1