ReactJS this.state为空

编程入门 行业动态 更新时间:2024-10-28 14:23:05
本文介绍了ReactJS this.state为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

首先说我是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为空

本文发布于:2023-07-22 03:47:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1183872.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   ReactJS   state

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!