所以我需要运行这行代码:
var vehicles = this.state.vehicles;
在渲染函数中:
render: function(){...}
我目前收到此错误:
Uncaught (in promise) TypeError: Cannot read property 'state' of undefined
尽管这条线有效:
this.setState({vehicles: json})
这也是代码的一部分:
getInitialState: function(){
this.render = this.render.bind(this)
return {
vehicles: []
}
}
如何修复此错误并访问数据?
最佳答案
您没有绑定(bind)渲染函数。我假设您正在使用 React.createClass
创建组件,因为您正在使用 getInitialState
来初始化状态。使用 React.createClass,React 会自动为您进行绑定(bind)。
即使您通过扩展 React.Component
创建组件,渲染方法和生命周期函数也会自动绑定(bind)到 React 组件上下文。
您的getInitialState
函数将只是
getInitialState: function(){
return {
vehicles: []
}
}
示例工作片段
var App = React.createClass({
getInitialState: function() {
console.log(this);
return {count: 0}
},
render: function() {
return <div>Count:{this.state.count}</div>
}
})
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>
关于reactjs - 从渲染函数访问状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45445298/