【发布时间】:2020-07-22 02:27:36
【问题描述】:
简化我是新手,在渲染数据集时,出现错误“无法读取未定义的属性映射/0”(两个独立的,在代码中注释)。真正困扰我的是,当 dataSource(在 this.state 中)在类组件之外声明为 const 时,一切正常,但它没有作为 App 类的 state 属性。
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>
【问题讨论】:
-
您的代码不那么可读,或者至少从反应的角度来看。我建议调查一下reactjs.org/docs/introducing-jsx.html
-
也可以试试
dataSource.levels.map或许... -
您的代码似乎不完整。例如,
columns已声明但从未使用过。它是如何使用的?所有App正在渲染的是Button,所以你有cmets 的那些行不会被执行。sorter()什么时候被调用?render: levels => ...什么时候被调用,你传递给它的级别是什么? -
@EvanMorrison 很抱歉没有澄清这一点。
sorter()和render会在return()主函数中渲染表格时自动调用,我现在附上表格渲染代码。
标签: javascript reactjs dictionary antd