【问题标题】:Why my this.state is null?为什么我的 this.state 为空?
【发布时间】:2018-06-26 17:01:30
【问题描述】:

我是 React 新手,我正在尝试从 websocket 渲染一个 json。

现在我可以使用这个从 websocket 获取 json:

 componentWillMount() {
    this.ws = new WebSocket('ws://10.77.0.79:1234')
    this.ws.onmessage = e => this.setState({data: Object.values((e.data))})
    this.ws.onerror = e => this.setState({ error: 'WebSocket error' })
    this.ws.onclose = e => !e.wasClean && this.setState({ error: `WebSocket error: ${e.code} ${e.reason}` })
  }

然后我需要映射这个 json,现在我正在使用这个:

 render() {
  // this is my json from websocket
      var json2 = {"Auth":{"status":"true","user":"gesplan","pass":"root"}}

       var arr = [];
  Object.keys(json2).forEach(function(key) {
      arr.push(json2[key]);
    });

    return <ul>{arr.map(item => <MyAppChild key={item.status} label={item.status} value={item.user} pass={item.pass}  />)} {this.state.data} </ul>;

  }
}

class MyAppChild extends React.Component {
  render() {
    return <li>{this.props.label + " - " + this.props.value + this.props.pass  } </li>;
  }
}

有了这个我可以渲染 var json2 的值。

我怎样才能用我的 this.state.data 做到这一点?当我为 this.state.data 更改 json2 时,它返回 null,但是如果我正常渲染,状态怎么可能为 null?

【问题讨论】:

  • 将初始状态数据设置为空数组,然后你可能不会遇到这个问题
  • 这样吗? this.state = { 数据:[] }
  • 我现在收到此错误:无法读取未定义的属性“状态”
  • 你到底在哪里得到这个错误

标签: json reactjs websocket state render


【解决方案1】:

首先将您的初始状态设置为一个空数组。新数据进来时追加数据:

constructor() {
    this.state = {
      data: []
    }
}

componentWillMount() {
    this.ws = new WebSocket('ws://10.77.0.79:1234')
    this.ws.onmessage = e => this.setState({
      data: [].concat(this.state.data, JSON.parse(e.data).Auth)
    })
    this.ws.onerror = e => this.setState({ error: 'WebSocket error' })
    this.ws.onclose = e => !e.wasClean && this.setState({ error: `WebSocket error: ${e.code} ${e.reason}` })
}

render() {
  return (
    <ul>
      {this.state.data.map(item =>
        <MyAppChild key={item.status} label={item.status} value={item.user} pass={item.pass}  />)
      }
    </ul>
  );
}

【讨论】:

  • @LucioZenir 更新
  • 现在我收到一个警告:警告:数组或迭代器中的每个孩子都应该有一个唯一的“键”道具。它呈现: undefined - undefinedundefined
  • 我想你可能不想使用Object.values(e.data)。试试我更新的编辑。
  • 我正在使用您更新的编辑,仍然返回 undefined = (
猜你喜欢
  • 2018-11-13
  • 2016-09-04
  • 2010-11-25
  • 2018-04-07
  • 2015-02-22
  • 2017-12-07
  • 2010-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多