尝试访问数组后,返回的 React 组件无法读取 null 的属性 '__reactInternalInstance$ [英] React component returning cannot read property '__reactInternalInstance$ of null after trying to access array

查看:16
本文介绍了尝试访问数组后,返回的 React 组件无法读取 null 的属性 '__reactInternalInstance$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有问题的组件.

const UserList = React.createClass({渲染:函数(){让列表;如果(this.props.data){theList=this.props.data.map(function(user, pos){返回 (<div className="row user"><div className="col-xs-1">{pos}</div><div className="col-xs-5">{user.username}</div><div className="col-xs-3">{user.recent}</div><div className="col-xs-3">{user.alltime}</div>

);}, 这个);} 别的 {theList = <div>我不知道了</div>;}控制台日志(列表);返回 (列表);}});

每当我尝试返回 {theList} 时,我都会收到 无法读取 null 的属性 '__reactInternalInstance$mincana79xce0t6kk1s5g66r' 错误.但是,如果我用静态 html 替换 {theList},console.log 会打印出我想要的正确对象数组.根据答案,我试图同时返回 {theList} 和 theList 但这没有帮助.

在这两种情况下,console.log 首先打印出 [],我认为这是因为 componentDidMount 包含我从服务器获取 json 的 ajax 调用,并且在第一次 render() 之前还没有触发.我试图检查this.props.data 为 null 但它没有帮助.

如果有帮助,这里是父组件:

const 排行榜 = React.createClass({getInitialState: 函数(){返回({数据:[],模式:0});},componentDidMount: 函数(){$.ajax({url: 'https://someurlthatreturnsjson',数据类型:'json',缓存:假,成功:功能(数据){this.setState({数据: 数据});}.bind(this),错误:函数(xhr,状态,错误){console.error('https://someurlthatreturnsjson', status, err.toString());}.绑定(这个)});},渲染:函数(){返回 (<div className="排行榜"><div className="row titleBar"><img src="http://someimage.jpg"></img>排行榜

<HeaderBar/><用户列表数据={this.state.data}/>

);}});

解决方案

好吧,这里有一些有趣的问题,但你如此接近.最重要的是,使用 react,您必须始终返回单个顶级元素(例如 div).所以,你的变量 theList 实际上是一个 div 数组.你不能直接返回那个.但是如果它包含在单个父 div 中,您可以返回它.

const mockData = [{用户名:'鲍勃',最近:'七',历史上:123,},{用户名:'sally mae',最近:'七',一直以来:133999,},];无功 $ = {阿贾克斯(选择){setTimeout(() => {opt.success(mockData);}, 200);}}const UserList = React.createClass({渲染:函数(){让列表;如果(this.props.data && this.props.data.length){theList = this.props.data.map(function(user, pos){返回 (<div key={user.username} className="row user"><div className="col">{pos}</div><div className="col">{user.username}</div><div className="col">{user.recent}</div><div className="col">{user.alltime}</div>

);});} 别的 {theList = <div>没有数据</div>;}返回<div>{theList}</div>;}});const 排行榜 = React.createClass({getInitialState: 函数(){返回({数据:[],模式:0});},componentDidMount: 函数(){$.ajax({url: 'https://someurlthatreturnsjson',数据类型:'json',缓存:假,成功:功能(数据){this.setState({数据: 数据});}.bind(this),错误:函数(xhr,状态,错误){console.error('https://someurlthatreturnsjson', status, err.toString());}.绑定(这个)});},渲染:函数(){返回 (<div className="排行榜"><用户列表数据={this.state.data}/>

);}});ReactDOM.render(<排行榜/>,document.getElementById('容器'));

.col {宽度:200px;向左飘浮;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script><div id="容器"><!-- 此元素的内容将替换为您的组件.-->

稍微解释一下小提琴.不要担心看起来很奇怪的 var $ 东西,我只是删除了 jQuery 的 ajax 方法,所以我可以在 200 毫秒后返回一些假数据.

另外,对我来说,jsfiddle 在我运行时给了我一条配置错误"的消息,但我关闭了消息,结果就在那里.不知道那是什么.

Here is the problematic component in question.

const UserList = React.createClass({
  render: function(){
    let theList;
    if(this.props.data){
      theList=this.props.data.map(function(user, pos){
        return (
          <div className="row user">
            <div className="col-xs-1">{pos}</div>
            <div className="col-xs-5">{user.username}</div>
            <div className="col-xs-3">{user.recent}</div>
            <div className="col-xs-3">{user.alltime}</div>
          </div>
        );
      }, this);
    } else {
     theList = <div>I don't know anymore</div>;
    }
    console.log(theList);
    return (
      theList
    );
  }
});

Whenever I attempt to return {theList}, I receive a Cannot read property '__reactInternalInstance$mincana79xce0t6kk1s5g66r' of null error. However, if I replace {theList} with static html, console.log prints out the correct array of objects that i want. As per the answers, I have tried to return both {theList} and theList but that didn't help.

In both cases, console.log first prints out [] which I assume is because componentDidMount contains my ajax call to get json from the server and has not fired yet before the first render(). I have tried to check against this.props.data being null but it does not help.

Here is the parent component if it helps:

const Leaderboard = React.createClass({
  getInitialState: function(){
    return ({data: [], mode: 0});
  },
  componentDidMount: function(){
    $.ajax({
      url: 'https://someurlthatreturnsjson',
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('https://someurlthatreturnsjson', status, err.toString());
      }.bind(this)
    });
  },
  render: function(){
    return (
      <div className="leaderboard">
        <div className="row titleBar">
          <img src="http://someimage.jpg"></img>Leaderboard
        </div> 
        <HeaderBar />
        <UserList data={this.state.data}/>
      </div>
    );
  }
}); 

解决方案

Ah OK, there were some interesting problems in here, but you were so close. The big one, with react you must always return a single top-level element (e.g. a div). So, your variable theList was actually an array of divs. You can't return that directly. But you can return it if it's wrapped in a single parent div.

const mockData = [
	{
  	username: 'bob',
    recent: 'seven',
    alltime: 123,
  },
	{
  	username: 'sally mae',
    recent: 'seven',
    alltime: 133999,
  },
];

var $ = {
	ajax(opt) {
  	setTimeout(() => {
    	opt.success(mockData);
    }, 200);
  }
}

const UserList = React.createClass({
  render: function(){
  	let theList;
    if (this.props.data && this.props.data.length) {
      theList = this.props.data.map(function(user, pos){
        return (
          <div key={user.username} className="row user">
            <div className="col">{pos}</div>
            <div className="col">{user.username}</div>
            <div className="col">{user.recent}</div>
            <div className="col">{user.alltime}</div>
          </div>
        );
      });
    } else {
      theList = <div>There is NO data</div>;
    }
    
    return <div>{theList}</div>;
  }
});

const Leaderboard = React.createClass({
  getInitialState: function(){
    return ({data: [], mode: 0});
  },
  componentDidMount: function(){
    $.ajax({
      url: 'https://someurlthatreturnsjson',
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('https://someurlthatreturnsjson', status, err.toString());
      }.bind(this)
    });
  },
  render: function(){
    return (
      <div className="leaderboard">
        <UserList data={this.state.data}/>
      </div>
    );
  }
}); 

ReactDOM.render(
  <Leaderboard/>,
  document.getElementById('container')
);

.col {
  width: 200px;
  float: left;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

<div id="container">
  <!-- This element's contents will be replaced with your component. -->
</div>

To explain the fiddle a little bit. Don't worry about the weird looking var $ stuff, I'm just stubbing out jQuery's ajax method so I can return some fake data after 200ms.

Also, for me jsfiddle gives me a 'bad config' message when I run it, but I close the message and the result is there. Don't know what that's about.

这篇关于尝试访问数组后,返回的 React 组件无法读取 null 的属性 '__reactInternalInstance$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆