我正在尝试路由链接并传递数据。 问题是当我在新闻组件上收到该消息时,我将其传递给它的所有东西都返回了未定义的内容。
app.js
<BrowserRouter>
<Route path="/news" component={News} />
</BrowserRouter>
parent.js
<NavLink to={{
pathname: '/news',
state : { all : this.props.content} // this is what I want to send and I receive it from another
}}>Todo</NavLink>
news.js
export default class News extends React.Component {
constructor(props){
super(props)
}
render(){
const foo = this.props.location.state
console.log(foo) // Cannot read property 'state' of undefined..
console.log(this.props.location) // return undefined
console.log(this.props) // return empty {}
return (
<div className='container'>
<section>
<h1>hello world </h1>
</section>
</div>
)
}
}
答案 0 :(得分:0)
我不确定parent.js
在您的网站结构中的位置。但是我为您做了codesandbox example。
我已经在parent.js
中定义了defaultProp,因此一些数据将传递到NavLink
,但是您应该能够根据需要重新构造示例。
https://codesandbox.io/s/jp4qr3q3ww?autoresize=1&expanddevtools=1&fontsize=14
app.js(index.js)
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route } from "react-router-dom";
import News from "./news.js";
import Parent from "./parent.js";
import "./styles.css";
function App() {
return (
<BrowserRouter>
<Route path="/" component={Parent} />
<Route path="/news" component={News} />
</BrowserRouter>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
parent.js
import React from "react";
import { NavLink } from "react-router-dom";
const Parent = props => (
<NavLink
to={{
pathname: "/news",
state: { all: props.content } // this is what I want to send and I receive it from another
}}
>
Todo
</NavLink>
);
Parent.defaultProps = {
content: "some content"
};
export default Parent;
news.js
import React from "react";
export default class News extends React.Component {
constructor(props) {
super(props);
}
render() {
const foo = this.props.location.state;
console.log(foo); // Cannot read property 'state' of undefined..
console.log(this.props.location); // return undefined
console.log(this.props); // return empty {}
return (
<div className="container">
<section>
<h1>hello world </h1>
</section>
</div>
);
}
}
答案 1 :(得分:0)
取决于您应用的结构,您的News
组件可能不会收到路由器道具。尝试如下声明您的Route
:
<Route
path="/news"
render={routerProps => <News {...routerProps}/>}
/>
或者,您可能想尝试使用withRouter
:
您可以通过
history
高阶组件访问<Route>
对象的属性和最接近的match
的{{1}}。每当渲染时,withRouter
会将更新后的withRouter
,match
和location
道具传递给包装的组件。
history