首先说我是ReactJS的新手,让我以此开头.我正在尝试通过制作一个使用React填充数据的简单站点来学习.我有一个JSON文件,其中包含将与map循环通过的链接数据.
Let me preface this by saying I am a novice to ReactJS. I am trying to learn by making a simple site that populates data using React. I have a JSON file that contains link data that will be looped through with map.
我尝试将其设置为组件状态,然后通过道具将其传递到导航栏链接,但我收到"Uncaught TypeError:无法读取null的'data'属性"
I have tried setting it as the components state then passing it to the navbar links via a prop but I am getting "Uncaught TypeError: Cannot read property 'data' of null"
我试图四处寻找解决方案,但找不到任何东西.
I tried to look around for solutions but could not find anything.
注意:当我尝试对对象进行硬编码并通过该对象映射时,它返回map的方式是不确定的.但是我不确定这与setState错误直接相关.
Note: When I try to hard code an object and map through it that way it returns map is undefined. However I am not sure that is directly related to the setState error.
/** @jsx React.DOM */ var conf = { companyName: "Slant Hosting" }; var NavbarLinks = React.createClass({ render: function(){ var navLinks = this.props.data.map(function(link){ return( <li><a href={link.target}>{link.text}</a></li> ); }); return( <ul className="nav navbar-nav"> {navLinks} </ul> ) } }); var NavbarBrand = React.createClass({ render: function(){ return( <a className="navbar-brand" href="#">{confpanyName}</a> ); } }); var Navbar = React.createClass({ getInitalState: function(){ return{ data : [] }; }, loadNavbarJSON: function() { $.ajax({ url: "app/js/configs/navbar.json", dataType: 'json', success: function(data) { this.setState({ data: data }); console.log(data); console.log(this.state.data); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, componentDidMount: function(){ this.loadNavbarJSON(); }, render: function(){ return( <nav className="navbar navbar-default navbar-fixed-top" role="navigation"> <div className="container-fluid"> <div className="navbar-header"> <NavbarBrand /> </div> <NavbarLinks data={this.state.data} /> </div> </nav> ); } }); var Header = React.createClass({ render: function(){ return( <Navbar /> ); } }); React.renderComponent( <Header />, document.getElementById('render') );推荐答案
使用ES6,必须在您的React组件类的构造函数中创建初始状态,如下所示:
Using ES6, the initial state must be created in your constructor for the React component class, like this:
constructor(props) { super(props) this.state ={ // Set your state here } }请参见本文档.
更多推荐
ReactJS this.state为空
发布评论