【发布时间】: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