javascript - this.state 在 React 组件渲染函数中未定义
问题描述
我是 ReactJS 的新手。以下功能运行良好:
_renderTable: function() {
return(
React.DOM.table(null,
React.DOM.thead( {onClick: this._sort},
React.DOM.tr(null,
this.props.headers.map(function (title, idx) {
if (this.state.sortby === idx) {
title += this.state.descending ? ' \u2191' : ' \u2193'
}
return React.DOM.th({key: idx}, title);
}, this)
)
),
React.DOM.tbody( {onDoubleClick: this._showEditor},
this._renderSearch(),
this.state.data.map(function (row, rowidx) {
return(
React.DOM.tr({key: rowidx},
row.map(function (cell, idx) {
var content = cell;
//To-Do editable field on double click
var edit = this.state.edit;
if (edit && edit.row === rowidx && edit.cell === idx) {
content = React.DOM.form({onSubmit: this._save},
React.DOM.input({
type: "text",
defaultValue: content,
})
);
}
return React.DOM.td({
key: idx,
"data-row": rowidx
}, content);
}, this)
)
);
}, this)
)
)
);
},
当我使用 babel 重写它时:
_renderTable: function() {
return(
<table>
<thead onClick={this._sort}>
<tr>{
this.props.headers.map(function (title, idx) {
if (this.state.sortby === idx) {
title += this.state.descending ? ' \u2191' : ' \u2193'
}
return <th key={idx}>{title}</th>
}, this)
}</tr>
</thead>
<tbody onDoubleClick={this._showEditor}>
{this._renderSearch()}
{console.log("Hello", this.state)}
{
this.state.data.map(function (row, rowidx) {
return(
<tr key={rowidx}>{
row.map(function (cell, idx) {
var content = cell;
console.log("Hello2", this);
var edit = this.state.edit;
if (edit && edit.row === rowidx && edit.cell === idx) {
content = <form onSubmit={this._save}>
<input type="text" defaultValue={content}>
</input>
</form>
}
return <td key={idx}>{content}</td>
})
}</tr>
);
})
}
</tbody>
</table>
);
},
我收到以下错误:
Uncaught TypeError: Cannot read property 'state' of undefined
替换var edit = this.state.edit;
为var edit = false;
删除错误。
搜索显示在函数正文中调用绑定this
的情况下,所以我尝试这样做但没有运气。不确定绑定中的问题,因为非 JSX 版本的代码工作正常。
解决方案
这确实是一个范围问题,在迭代 map 时,您正在声明一个函数,this
在该函数内部使用将引用不同的上下文。您可以使用箭头功能( ) => { ... }
this.state.data.map((row, rowidx) => {
...
row.map((cell, idx) => {
...
}
})
this
或者在 map 函数之前在另一个变量中分配引用var self = this
var self = this
this.state.data.map(function (row, rowidx) {
...
row.map((cell, idx) => {
var edit = self.state.edit;
...
}
})
推荐阅读
- intellij-idea - 如何在 IntelliJ 中现有的代码中添加 Aspose?
- excel - 索引匹配查找 - LAST 值
- javascript - 使用 jquery 获取 id 不起作用
- reactjs - 使用 Flowtype 覆盖 React-Redux Connect()
- r - 从renderText()输出的R Shiny分割文本行
- python - django 如何将自己模型的字段列表添加到我的模型中?
- html - HTML5 音频 - 在 Safari 上搜索后 currentTime 属性错误
- angular - Angular 组件 - 在运行时创建或使用数据参数静态创建
- oauth - 社交 oauth 如何真正发挥作用?
- node.js - 运行 2 个重复的异步函数,而不在 await 上暂停另一个