javascript - React类组件中的Javascript“无法读取未定义的属性”
问题描述
简化我是新来的反应,当我渲染数据集时,我收到错误“无法读取未定义的属性映射/0”(两个单独的,在代码中注释)。真正困扰我的是,当 dataSource(在 this.state 中)被声明为const
类组件之外时,一切都运行良好,但它不能作为 App 类的状态属性。
function compare(a, b) {
var n = -1, m = 0;
if (a === "important") {n = 2;} else if (a === "normal") {n = 1;} else {n = 0;}
if (b === "important") {m = 2;} else if (b === "normal") {m = 1;} else {m = 0;}
return n - m;
}
class App extends React.Component {
state = {
dataSource: [
{key: "1", title: "Call Uber eats w/o my parents", levels: ["important"]},
],
count: 2,
};
handleAdd = () => {
const { count, dataSource } = this.state;
const newData = {
key: count, name: `Edward King ${count}`, age: 32, address: `London, Park Lane no. ${count}`
};
this.setState({dataSource: [...dataSource, newData], count: count + 1});
};
render() {
const columns = [
{
title: "Level", dataIndex: "levels", key: "levels",
sorter: (a, b) => compare(a.levels[0], b.levels[0]), // cannot read property '0' of undefined
render: levels => (
<>
{levels.map(level => {
let color = ""; // cannot read property 'map' of undefined
if (level === "important") {color = "red";}
else if (level === "normal") {color = "blue";}
return (
<Tag color={color} key={level}>{level.toUpperCase()}</Tag>
);
})}
</>
)
},
];
return (
<Button onClick={this.handleAdd} type="primary">Add a row</Button> // Original call
);
}
}
我所知道的是,我必须以某种方式从此类的状态中检索数据以防止未定义的属性,但是当我将参数(不是实际对象)传递给函数时我感到困惑,它仍然引发了上述错误。
提前谢谢了。
编辑 这是返回函数的完整代码。这在第一次迭代中不包括在内,现在包括在内(感谢编辑)。
<Row justify="center" align="top">
<Col style={{ maxWidth: 1080 }}>
<Space style={{ marginBottom: 16 }}>
<Button onClick={this.handleAdd} type="primary">
Add a row
</Button>
<Button onClick={this.clearFilters}>Clear filters</Button>
<Button onClick={this.clearAll}>Clear filters and sorters</Button>
</Space>
<Table columns={columns} dataSource={this.state.dataSource}/>
</Col>
</Row>
解决方案
实际上,您正在直接访问级别属性,该属性是状态中 dataSource 数组中对象的一部分。这就是为什么它给出 undefined on 的错误levels
。
在渲染中,先获取状态——
const levelsArr = this.state.dataSource[0].levels;
然后尝试类似这样的代码compare(a.levelsArr[0], b.levelsArr[0])
还{levelsArr && levelsArr.map(level => {
推荐阅读
- c++ - 在恒定时间内修剪 C++ 字符串
- raku - perl6/raku:如何限制变量中允许的值?
- qt - 你如何在 QMenuBar 中放置一个组框?
- php - 有没有一种简短的方法来检查值的独特性而不使用 PHP 中的“if”和多个“and”?
- android - 每次用户打开应用程序时重新加载 firebase 用户
- reinforcement-learning - 近端策略优化中的目标函数
- python - ImportError:无法导入名称 - 两个具有相同名称的模块
- django - RunAsUser 问题和单击负载均衡器的外部 IP -> 在 GKE (Kubernetes) 上部署 Django 应用程序时出现错误请求 (400) 并且数据库连接失败:
- jenkins - 对于詹金斯版本。1.630,我安装了 Delivery Pipeline 插件,现在 jenkins 无法启动并出现以下错误
- reactjs - 渲染中未更新状态。+ 还原