【问题标题】:React Router and passing props to other component反应路由器并将道具传递给其他组件
【发布时间】:2020-05-30 18:04:57
【问题描述】:

我在一个组件中有一个按钮,单击时我想转到另一个组件并将状态传递给该组件。

是这样的:

import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import AddNewQuestionPage from 'AddNewQuestionPage';

class AddQuestions extends Component {
  state = {
    questions: []
  };

  routeChange = () => {
    let path = `/admin/add-new-question`;
    this.props.history.push(path);
  }

  render() {
    return (
      <>
       <button onClick={this.routeChange}>
          Add new question
       </button>
       <BrowserRouter>
        <Route exact={true} path='/admin/add-new-question' component={AddNewQuestionPage}/>
       </BrowserRouter>
      </>
    )
  }
}

而且它不起作用。单击时,我转到 add-new-question url,但组件 AddNewQuestionPage 不呈现。如果我将 Route 不是放在 AddQuestions 组件中,而是放在 App 组件中,它就可以工作。它是整个应用程序的主要组件,使用 Switch,还设置了其他路由。

但是,如果它是从 App 组件呈现的,我不知道如何将状态问题传递给 AddNewQuestionPage 组件?我不能这样做:

<Route path='/admin/add-new-question' render={(props) => <AddNewQuestionPage {...props} questions={questions} />

因为它不知道什么是“问题”。将状态提升到主要组件对我来说似乎不是一个好的解决方案。我正在搜索,但我找不到如何做到这一点......

【问题讨论】:

    标签: reactjs react-router react-props react-state


    【解决方案1】:

    您应该在传递给组件的问题上使用this 关键字。

    像这样的

    
    <Route path='/admin/add-new-question' render={(props) => <AddNewQuestionPage {...props} questions={this.state.questions} />
    
    

    【讨论】:

    • 谢谢,现在它似乎工作了,但是如果我在 AddNewQuestionPage 组件中执行 console.log(this.props.questions),它是未定义的。
    • 你确定你在构造函数和super中传递了props吗?
    • 我在这个项目中根本不使用构造函数和超级。我确实喜欢这里的描述:hackernoon.com/… 但是现在我也尝试了构造函数,它没有改变任何东西。当我做 console.log(this.props) 有问题 prop 但它的值未定义。
    【解决方案2】:

    使用 react-router dom 的最佳方式是:

    1. 始终将 make 作为所有组件的父组件。
    2. 通过单击某种组件(按钮...)来更改路径的最佳方法是您的标签

    请查看本指南:https://reacttraining.com/react-router/web/guides/quick-start

    【讨论】:

    • 感谢您的回答。在我的应用中,App 组件是所有组件的父级。我不明白你在说什么“你的标签”:) 你能解释一下吗?我正在阅读文档,但找不到解决方案。
    猜你喜欢
    • 2020-03-26
    • 2015-09-01
    • 2017-10-01
    • 1970-01-01
    • 2019-08-15
    • 2018-08-22
    • 2016-09-30
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多