我是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的值。
我怎么能用my.state.data做到这一点?当我为this.state.data更改json2时,它返回一个null,但如果我正常呈现它,状态如何为null?
答案 0 :(得分: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>
);
}