函数作为 React 子函数无效.通过常量而不是函数进行条件渲染



试图从所有类似的问题中学习,但所有或大部分都是关于通过在JSX中的名称后添加((来调用函数。 我不确定为什么在我的场景中出现问题。我必须通过条件 JSX 放置一个警报列表,其中 [警报.js] 只是导出一个数组;

export default [{ "alert_name": "HeavyRain", ...},{ "alert_name": "Cyclone", ...},{ "alert_name": CloudBurst", ...}]

条件 JSX 显示(可能导致问题(:

class dashalert extends Component {
render() {
const alerts = Alert.map((alert, idx) => {
let icon = ['r-margin', 'wi'];
if (alert.alert_name === 'HeavyRain') icon = [...icon, 'wi-rain'];
else if (alert.alert_name === 'Cyclone') icon = [...icon, 'wi-hurricane'];
else if (alert.alert_name === 'CloudBurst') icon = [...icon, 'wi-thunderstorm'];
return (
<Col key={idx}>
<Card>
<Card.Body>
<h3><i className={icon.join(' ')} /> {alert.alert_name}</h3>                       
</Card.Body>
</Card>
</Col>
);
});
return (
<React.Fragment>
{alerts}
</React.Fragment>
);
}
}
export default dashalert;

主组件调用此显示器:

class MyDashboard extends React.Component {
render() {
return (
<Aux>
<Row>
{dashalerts}
</Row>
</Aux>
);
}
}
export default MyDashboard;

无法弄清楚我们为什么错误:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
in div (created by Row)
in Row (created by Context.Consumer)
in ForwardRef(Bootstrap(Row)) (at Dashboard/index.js:18)
in Aux (at Dashboard/index.js:17)
in MyDashboard (at AdminLayout/index.js:53)
dashAlerts

是一个组件,你应该把它渲染成一个组件。另请注意,React 组件名称必须带有大写字母。

您可以将代码更新为如下所示

import DashAlerts from '/path/to/dashalert';
class MyDashboard extends React.Component {
render() {
return (
<Aux>
<Row>
<Dashalerts />
</Row>
</Aux>
);
}
}
export default MyDashboard;

最新更新