【发布时间】:2019-06-08 10:35:34
【问题描述】:
我正在使用 React Router 创建一个多页面应用程序。我的主要组件是<App/>,它将所有路由呈现到子组件。我正在尝试通过路由传递道具,并且基于我所做的一些research,子组件利用传递的道具的最常见方式是通过它们继承的this.props.route 对象。但是,这个对象对我来说是未定义的。在子组件中的 render() 函数中,我 console.log(this.props) 并返回一个看起来像这样的对象
{match: Object, location: Object, history: Object, staticContext: undefined}
看起来根本不像我预期的道具。这是我的详细代码。
父组件(我试图在我的所有子组件中将“hi”这个词作为一个名为“test”的道具传递):
import { BrowserRouter as Router, HashRouter, Route, Switch } from 'react-router-dom';
import Link from 'react-router';
import React from 'react';
import Home from './Home.jsx';
import Nav from './Nav.jsx';
import Progress from './Progress.jsx';
import Test from './Test.jsx';
export default class App extends React.Component {
constructor() {
super();
this._fetchPuzzle = this._fetchPuzzle.bind(this);
}
render() {
return (
<Router>
<div>
<Nav />
<Switch>
<Route path="/" exact test="hi" component={Home} />
<Route path="/progress" test="hi" component={Progress} />
<Route path="/test" test="hi" component={Test} />
<Route render={() => <p>Page not found!</p>} />
</Switch>
</div>
</Router>
);
}
}
孩子:
import React from 'react';
const CodeMirror = require('react-codemirror');
import { Link } from 'react-router-dom';
require('codemirror/mode/javascript/javascript')
require('codemirror/mode/xml/xml');
require('codemirror/mode/markdown/markdown');
export default class Home extends React.Component {
constructor(props) {
super(props);
console.log(props)
}
render() {
const options = {
lineNumbers: true,
theme: 'abcdef'
// mode: this.state.mode
};
console.log(this.props)
return (
<div>
<h1>First page bro</h1>
<CodeMirror value='code lol' onChange={()=>'do something'} options={options} />
</div>);
}
}
我对 React 很陌生,所以如果我遗漏了一些明显的东西,我深表歉意。 谢谢!
【问题讨论】:
-
您想从
route对象中提取什么信息?在 react-router v4 中,您应该能够从match或location检索相同的信息 -
@AnthonyKong 我正在尝试提取“测试”属性。
<Route path="/" exact test="hi" component={Home} />。我的印象是,渲染的<Home/>组件可以访问持有该值的对象。我查看了match和location对象,但没有找到我的道具。 -
match.params.test怎么样? -
不知道为什么该值不存在,但替代方法是,像这样传递该值:
<Route path="/test" render={(props) => <Test {...props} test="hi"/>} />并通过this.props.test访问它。 -
@MayankShukla 谢谢。这交付了。奇怪的是,使用其他技术没有显示该值。
标签: javascript reactjs react-router react-router-v4