我正在父组件中渲染图表。当我试图在子组件中访问this.props.onUpdate()时,出现错误"无法读取属性' props'未定义"
我必须根据开始和结束时间更新图表数据。
子组件
var React = require('React');
var ReactDOM = require('ReactDOM');
var Chart = require('react-google-charts').Chart;
var $ = require('jquery');
var LChart = React.createClass({
getInitialState: function() {
return {
rows: [],
}
},
componentWillMount: function () {
var _this = this;
var request = function () {
this.props.onUpdate();
$.post("/url" ,{'start':this.props.sTime, 'end':this.props.eTime }, function (result) {
_this.setState({
rows: result.data
});
});
setTimeout(request, 10000);
};
request();
},
render: function() {
return (
<div id="chart_widget" >
<Chart chartType="LineChart"
rows={this.state.rows}
columns={this.props.columns}
options={this.props.options}
width={this.props.width}
height={this.props.height} />
</div>
);
}
});
module.exports = LChart;
父组件:
var React = require('React');
var LChart = require('LChart');
var Parent = React.createClass({
getInitialState: function()
{
return ({
columns: [
{
'type': 'datetime',
'label' : 'Date'
},
{
'type' : 'number',
'label' : Val
}
],
options:
{
hAxis:{format:'HH:mm'},
},
date: new Date(),
eTime: date.getTime(),
sTime: eTime - (60000 * 5),
});
},
onUpdate: function(val){
this.setState({
date: new Date(),
eTime: date.getTime(),
sTime: eTime - (60000 * range),
});
},
render: function () {
return (
<div >
<LChart width="500px" height="400px"
date={this.state.date}
sTime={this.state.sTime}
eTime={this.state.eTime}
columns={this.state.columns}
options={this.state.options}
onUpdate={this.onUpdate}/>
</div>
);
}
});
module.exports = Parent;
答案 0 :(得分:1)
您应该将request
绑定到LChart
组件。
var LChart = React.createClass({
getInitialState: function() {
return {
rows: [],
}
},
componentWillMount: function () {
var _this = this;
var request = function () {
this.props.onUpdate();
$.post("/url" ,{'start':this.props.sTime, 'end':this.props.eTime }, function (result) {
_this.setState({
rows: result.data
});
});
setTimeout(request, 10000);
};
request = request.bind(this);
request();
},
render: function() {
return (
<div id="chart_widget" >
<Chart chartType="LineChart"
rows={this.state.rows}
columns={this.props.columns}
options={this.props.options}
width={this.props.width}
height={this.props.height} />
</div>
);
}
});
此外,在您的父组件中,在new Date
来电之外声明setState
。