以下是我正在做的事情的愚蠢版本
点击“跳过”按钮时,我从随机“页面”获取信息,然后使用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”?
出了什么问题?
答案 0 :(得分:2)
在第一次渲染时,您的page
州没有任何link
属性,因此null
组件的Link
(无效)值。
您可以通过在初始值中添加一个来解决此问题:
getInitialState () {
return {
page: {
title: "hi",
description: "Homepage",
link: "/0_home"
}
}
},
答案 1 :(得分:1)
this.setState({page: pages[randomNum]})
中的{p> getRandomPage()
。因此,当this.state.page.link
为undefined
时,初始渲染会出现错误,但只要您点击该按钮,您的this.state.page.link
就会出现问题。
更改您的初始状态:
getInitialState () {
return {
page: {
title: 'something...',
link: '/1_page_one',
description: 'something...'
}
}
}