我正在使用react和react-router。
我试图在反应路由器的“链接”中传递属性
var React = require('react');
var Router = require('react-router');
var CreateIdeaView = require('./components/createIdeaView.jsx');
var Link = Router.Link;
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var App = React.createClass({
render : function(){
return(
<div>
<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
<RouteHandler/>
</div>
);
}
});
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="ideas" handler={CreateIdeaView} />
<DefaultRoute handler={Home} />
</Route>
);
Router.run(routes, function(Handler) {
React.render(<Handler />, document.getElementById('main'))
});
“Link”呈现页面,但不将属性传递给新视图。
下面是视图代码
var React = require('react');
var Router = require('react-router');
var CreateIdeaView = React.createClass({
render : function(){
console.log('props form link',this.props,this)//props not recived
return(
<div>
<h1>Create Post: </h1>
<input type='text' ref='newIdeaTitle' placeholder='title'></input>
<input type='text' ref='newIdeaBody' placeholder='body'></input>
</div>
);
}
});
module.exports = CreateIdeaView;
如何使用“链接”传递数据?
打印稿
对于很多答案中提到的方法,
<Link
to={{
pathname: "/my-path",
myProps: {
hello: "Hello World"
}
}}>
Press Me
</Link>
我得到了错误,
对象文字可能只指定已知的属性,'myProps'不存在类型'LocationDescriptorObject | ((location: location) => LocationDescriptor)'
然后我查看了他们为同样目的提供的官方文件。
它是这样工作的,
<Link
to={{
pathname: "/my-path",
state: {
hello: "Hello World"
}
}}>
Press Me
</Link>
在你的下一个组件中,你可以得到如下的值,
componentDidMount() {
console.log("received "+this.props.location.state.hello);
}
路线:
<Route state={this.state} exact path="/customers/:id" render={(props) => <PageCustomer {...props} state={this.state} />} />
然后可以像这样访问PageCustomer组件中的参数:
例如,PageCustomer组件中的api调用:
axios({
method: 'get',
url: '/api/customers/' + this.props.match.params.id,
data: {},
headers: {'X-Requested-With': 'XMLHttpRequest'}
})
打印稿
对于很多答案中提到的方法,
<Link
to={{
pathname: "/my-path",
myProps: {
hello: "Hello World"
}
}}>
Press Me
</Link>
我得到了错误,
对象文字可能只指定已知的属性,'myProps'不存在类型'LocationDescriptorObject | ((location: location) => LocationDescriptor)'
然后我查看了他们为同样目的提供的官方文件。
它是这样工作的,
<Link
to={{
pathname: "/my-path",
state: {
hello: "Hello World"
}
}}>
Press Me
</Link>
在你的下一个组件中,你可以得到如下的值,
componentDidMount() {
console.log("received "+this.props.location.state.hello);
}
在我的情况下,我有一个空道具的功能组件,这解决了它:
<Link
to={{
pathname: `/dashboard/${device.device_id}`,
state: { device },
}}
>
View Dashboard
</Link>
在你的函数组件中,你应该有这样的东西:
import { useLocation } from "react-router"
export default function Dashboard() {
const location = useLocation()
console.log(location.state)
return <h1>{`Hello, I'm device ${location.state.device.device_id}!`}</h1>
}