我有下面的反应代码,当变量日志是字符串,即注释代码时工作正常,但是一旦我用数组替换日志,我就会收到错误,
import React from "react";
export default class WelcomeComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
// logs :''
logs: []
};
}
componentDidMount() {
var socket = io('http://localhost:11001');
socket.on('news', (data) => {
data = JSON.parse(data);
this.setState({
logs: this.state.logs.push(data)
// logs: data + this.state.logs
});
});
}
render() {
return (<div> {this.state.logs}</div>);
}
}
将日志作为数组,它会产生以下错误,
未捕获的TypeError:_this2.state.logs.push不是函数(...)
任何人都可以帮忙。
答案 0 :(得分:2)
尝试使用不变性方法:
socket.on('news', (data) => {
data = JSON.parse(data);
const newLogs = [...this.state.logs, data]
this.setState({
logs: newLogs
// logs: data + this.state.logs
});
});
答案 1 :(得分:0)
你正在改变组件的状态,这是一个很大的问题。试试React Immutability Helpers
import React from "react";
import update from 'react-addons-update';
export default class WelcomeComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
// logs :''
logs: []
};
}
componentDidMount() {
var socket = io('http://localhost:11001');
socket.on('news', (data) => {
data = JSON.parse(data);
this.setState({
logs: update(this.state.logs, {$push: [data]});
});
});
}
render() {
return (<div> {this.state.logs}</div>);
}
}