下面是我正在做的事情的简化版本
当单击“跳过”按钮时,我将从随机“页面”获取信息,然后使用 this.state 来显示它。
import React from "react"
import { Link } from 'react-router'
const MyComponent = React.createClass({
getRandomPage () {
var pages = [
{
link: "/1_page_one",
title: "title one",
description: "Description1"
},
{
link: "/2_page_two",
title: "title Two",
description: "Description2"
},
{
link: "/3_page_three",
title: "title three",
description: "Description3"
}
]
var randomNum = Math.floor(Math.random() * pages.length);
this.setState({page: pages[randomNum]});
},
getInitialState () {
return {
page: "hi"
}
},
render () {
console.log(this.state.page.link);
return (
<div>
<div>
<li><Link to="/1_page_one"><button type="submit">To Page</button></Link></li>
<li><button onClick={this.getRandomPage} type="submit">Skip</button></li>
</div>
</div>
<div>
<h1>{this.state.page.title}</h1>
<h2>Description</h2>
<div>
{this.state.page.description}
</div>
</div>
);
}
});
export default MyComponent;
一切似乎都工作正常,除非我尝试改变
<li><Link to="/1_page_one"><button type="submit">To Page</button></Link></li>
到
<li><Link to={this.state.page.link}><button type="submit">To Page</button></Link></li>
我收到一条错误消息:
main.js:8715 Warning: Failed prop type: Invalid prop `to` supplied to `Link`.
in Link (created by ChallengeBoxes)
in ChallengeBoxes (created by MainContent)
in div (created by MainContent)
in MainContent (created by RouterContext)
in div (created by App)
in App (created by RouterContext)
in RouterContext (created by Router)
in Router
但是当检查值时
console.log(this.state.page.link);
状态中的链接是正确的字符串,例如“/1_page_one”?
出了什么问题?
最佳答案
在第一次渲染时,您的 page
状态没有任何 link
属性,因此为 null
(无效)值赋予 Link
组件。
您可以通过在初始值中加一来解决这个问题:
getInitialState () {
return {
page: {
title: "hi",
description: "Homepage",
link: "/0_home"
}
}
},
关于javascript - react : Invalid prop type Link when using JSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39207370/