【发布时间】: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