【问题标题】:React-router route props not passedReact-router 路由道具未通过
【发布时间】:2017-05-31 10:32:35
【问题描述】:

我正在使用 componentDidMount 从 firebase 获取数据并使用获取的数据设置组件状态

  componentDidMount() {
  this.state.firebase.database().ref().on("value", function(snapshot) {
  let data = snapshot.val()

  // Authors
  this.setState({authors: data.Author})

然后在渲染方法中我有这个

{
    console.log(this.state.authors)
}
<Route path="/author/:authorId" component={AuthorPage} authors={this.state.authors} />

在 AuthorPage 组件中我有这个

render() {
    console.log(this.props.route)
    return (....

控制台输出是

Object {authorId: Object} // This is for this.state.authors
Object {path: "/author/:authorId", authors: undefined, component: function} // this is for this.props.route

如你所见,this.state.authors 有一个值,但在作为路由道具传递给组件时变得未定义。这在我之前从未发生过,即使在与其他路线相同的应用程序中也是如此。

【问题讨论】:

  • this.setState({authors: data.Author}) 之前执行console.log(data.Author) 并检查其返回的值。你有什么错误吗?
  • 不,状态已正确分配,我检查了 React 开发工具。路由器出现问题
  • 其他地方也有同样的工作方式?我可以建议一个替代解决方案。
  • 替代品很多,这不是问题,但是为什么会出现这个问题。想知道

标签: javascript reactjs firebase firebase-realtime-database react-router


【解决方案1】:

由于某种原因,这解决了问题

  let authorsArray = data.Author
  let aths = this.state.authors
  for(var j in authorsArray) {
    aths[j] = authorsArray[j]
  }
  this.setState({authors: aths})

有人知道为什么吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2021-01-09
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多