我在运行 React 组件时遇到问题,因为我收到语法错误:
编译失败。
./app/javascript/RoastsJson/index.jsx Module build failed: SyntaxError: Unexpected token (6:10)
4 | class RoastsJson extends React.Component {
5 |
> 6 | render: function() {
| ^
7 | roasts = this.props.roasts.map( function(roast) {
8 | return (
9 | <tr key={roast.id}> @ ./app/javascript/packs/roastsjson.jsx 3:0-36 @ multi (webpack)-dev-server/client?http://localhost:3035 ./app/javascript/packs/roastsjson.jsx
只是不明白为什么这会失败...我不相关,但我在播放带有const = url
的文件时遇到了同样的错误,错误指向 URL 中的 u。
app/javascript/RoatsJson/index.jsx
import React from 'react'
import ReactDom from 'react-dom'
class RoastsJson extends React.Component {
render: function() {
roasts = this.props.roasts.map( function(roast) {
return (
<tr key={roast.id}>
<td>{roast.name}</td>
</tr>
);
console.log(roast);
});
return (
<div>
<h1>Roasts</h1>
<div id="roasts">
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
{roasts}
</tbody>
</table>
</div>
</div>
);
}
};
export default RoastsJson
我知道我可以(应该(删除function
,例如:
render() {
roasts = this.props.roasts.map( function(roast)
但这随后会在 conosle 中抛出以下内容:
unreachable code after return statement
上下文我正在尝试将一个名为roasts的Rails 5.1资源拉入这个反应组件中。 在我的roasts_controller.rb
:
def index
@roasts = Roast.all
render component: 'roatsjson', props: {roasts: @roasts}
end
我可以看到的问题是您的组件中未定义的烘焙。渲染数组的更好方法是使用数组并将元素推送到其中并打印出来。
还要开始使用箭头函数来避免范围问题和函数绑定。
检查下面更新的代码,它应该可以工作。
class RoastsJson extends React.Component {
render() {
let roasts = []
this.props.roasts.map((roast) => {
roasts.push(
<tr key={roast.id}>
<td>{roast.name}</td>
</tr>
)
});
return (
<div>
<h1>Roasts</h1>
<div id="roasts">
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
{roasts}
</tbody>
</table>
</div>
</div>
);
}
};
export default RoastsJson
似乎你传递了一个意想不到的roasts
道具。你应该尝试对你的道具进行一些检查,例如使用prop-types
库。
此外,对无状态组件使用纯 fonction 通常是一种很好的做法(请参阅 reactpatterns.com(。这里有一个,未经测试:
import React from 'react';
import PropTypes from 'prop-types';
const RoastsJson = ({ roasts }) => (roasts && (<div>
<h1>Roasts</h1>
<div id="roasts">
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
{
roasts.map(({id, name}) => <tr key={id}>
<td>{name}</td>
</tr>)
}
</tbody>
</table>
</div>
</div>));
RoastsJson.propTypes = {
roasts: PropTypes.array
};
export default RoastsJson;