React:无法访问存储在状态中的属性>对象

时间:2017-05-31 16:32:35

标签: javascript reactjs react-native

我得到我的JSON数据:

const channel = pusher.subscribe("channel");
channel.bind("event", data => {
  this.setState({ data }); //this data is an object
 //the above code is in a componentDidMount or componentWillMount method.

这就是我想做的事。

render() {
  return <Text> {this.state.data.high} </Text>
}

render() {
  return <Text> {this.state.data["high"]} </Text>
}

然而,没有显示任何内容。

这有效:

render() {
  return <Text> {JSON.stringify(this.state.data)} </Text>
}

这是我的初始状态

state = {
  data: []
};

编辑:数据存在且成功接收并添加到状态。我似乎无法访问它。

编辑2:我可以访问数据(可以登录到控制台)。但是,它不能由<Text />组件显示。

3 个答案:

答案 0 :(得分:1)

<强>解决

原来我的Text组件没有正确设置,这就是为什么它没有显示。

答案 1 :(得分:0)

我通常这样做以显示json数据看看

constructor(props) {
  super();
  const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
  this.state = {
    dataSource: ds.cloneWithRows([
      ''
    ]),
  }
}

...请求

.then((responseData) => {
  var arrayOutput=[];
  for (var k in responseData)
   arrayOutput.push(responseData[k]);

  this.setState({
     dataSource: this.state.dataSource.cloneWithRows(arrayOutput)
  });
})

然后我只使用ListView来显示数据

<ListView
   dataSource={this.state.dataSource}                            
   renderRow={(rowData) =>
   <Text>{rowData.id}</Text>                         
   <Text>{rowData.name}</Text>                         
}/>

答案 2 :(得分:0)

正如其中一条评论所提到的,您的州应该使用空的object进行初始化,而不是array

确保通过在回调中放置断点或console.log来调用绑定到订阅的事件:

channel.bind('event', data => {
    this.setState({ data });
});

要尝试的事情 -

  • 数据的回调肯定会被解雇吗?
  • 返回回调的数据肯定是一个对象,不需要JSON.parse吗?
  • 如果将初始状态设置为{data: { high: 'SOME TEXT' } }
  • ,是否有效
  • <Text>中取出<div>并尝试使用<Text>// Taken from BS boilerplate var _createClass = function () { // <-- this function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); // <-- and this 组件中是否有任何特殊逻辑可能导致其道具更改时无法更新?< / LI>

编辑:由于提供了额外信息而删除了示例组件

相关问题