【发布时间】:2016-07-16 06:17:08
【问题描述】:
我收到以下错误:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
我也从 React 得到这个警告:
Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
我遇到的实际问题(正如我通过调试所理解的那样)是我不能将类作为参数传递,如下所示:<BigCard pokemon={result} />,因为这里的结果是类的对象。我应该怎么做才能使其正常工作。有没有将类作为参数传递的最佳实践?
我有这个组件:
export var BigCard = React.createClass({
render: function() {
var rows = [];
var pokemon = this.props.pokemon;
for (var variable in pokemon) {
if (pokemon.hasOwnProperty(variable) && variable.toString() !== 'id' && variable.toString !== 'name' && variable.toString !== 'image' && variable.toString !== 'types') {
rows.push(
<tr>
<td class='mdl-data-table__cell--non-numeric'>
{variable}
</td>
<td>
{pokemon[variable]}
</td>
</tr>
)
}
}
return (
<div class='mdl-card mdl-shadow--4dp'>
<div class='mdl-card__title'>
<img src={pokemon.image.src} alt='Pokemon' class='bigCard__img'/>
</div>
<h2 class='mdl-card__title-text'></h2>
<div class='mdl-card__supporting-text'>
<table class='mdl-data-table mdl-js-data-table'>
<thead>
<tr>
<th class='mdl-data-table__cell--non-numeric'>Type</th>
<th class='mdl-data-table__cell--non-numeric'>{pokemon.types}</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
</div>
);
}
});
我有以下代码,我想运行:
import React from 'react';
import ReactDOM from 'react-dom';
import * as DataLogic from './modules/data-logic.js';
import SmallCard from './components/SmallCard.jsx';
import BigCard from './components/BigCard.jsx';
DataLogic.getPokemonById(3).then((result) => {
ReactDOM.render(
<BigCard pokemon={result} />,
document.getElementById('bigCard')
);
}).catch((error) => console.log(`${error} in main.js`));
getPokemonById 的结果是DetailedPokemon 类的对象。这是我的类,用作视图模型:
export default class DetailedPokemon {
constructor(id, name, image, types, attack, defense, hp, spAttack, spDefense, speed, weight, totalMoves) {
this.id = id;
this.name = name;
this.image = image;
this.types = types;
this.attack = attack;
this.defense = defense;
this.hp = hp;
this.spAttack = spAttack;
this.spDefense = spDefense;
this.speed = speed;
this.weight = weight;
this.totalMoves = totalMoves;
}
}
我希望,我清楚地解释了一切。你能帮我解决我的问题吗?
【问题讨论】:
-
您遇到的错误是什么?
JSON.parse用于解析包含 JSON 的 strings。如果result是一个对象,那么你不应该将它传递给JSON.parse。 -
@FelixKling 谢谢你,我已经编辑了问题!
标签: javascript oop reactjs ecmascript-6