我在这里做一个 React 课程,入门文件一直给我这个错误:
类型错误: 无法读取未定义的属性"0">
从这个起始代码:
import React from 'react'
import ReactDOM from 'react-dom'
const notes = [
{
id: 1,
content: 'HTML is easy',
date: '2019-05-30T17:30:31.098Z',
important: true
},
{
id: 2,
content: 'Browser can execute only Javascript',
date: '2019-05-30T18:39:34.091Z',
important: false
},
{
id: 3,
content: 'GET and POST are the most important methods of HTTP protocol',
date: '2019-05-30T19:20:14.298Z',
important: true
}
]
const App = (props) => {
const { notes } = props
return (
<div>
<h1>Notes</h1>
<ul>
<li>{notes[0].content}</li>
<li>{notes[1].content}</li>
<li>{notes[2].content}</li>
</ul>
</div>
)
}
ReactDOM.render(
<App notes={notes} />,
document.getElementById('root')
)
上面的代码显示:
尝试导入错误:"./App"不包含默认导出 (作为"应用"导入(
我尝试通过添加导出默认应用程序进行修改,并收到:
类型错误: 无法读取未定义的属性"0">
如何解决这个问题?
您引用的链接中的代码只是完整的index.js
文件。
如果您希望代码是模块化的,并且希望分离出App
组件,在这种情况下,您应该这样做,
索引.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import App from "./App"; //import your component (imported without { }, because App component exported as default)
const notes = [
{
id: 1,
content: 'HTML is easy',
date: '2019-05-30T17:30:31.098Z',
important: true
},
{
id: 2,
content: 'Browser can execute only Javascript',
date: '2019-05-30T18:39:34.091Z',
important: false
},
{
id: 3,
content: 'GET and POST are the most important methods of HTTP protocol',
date: '2019-05-30T19:20:14.298Z',
important: true
}
]
//Pass the props here
render(<App notes={notes}/>, document.getElementById('root'));
应用.js
import React from 'react'
const App = (props) => {
const { notes } = props
return (
<div>
<h1>Notes</h1>
<ul>
<li>{notes[0].content}</li>
<li>{notes[1].content}</li>
<li>{notes[2].content}</li>
</ul>
</div>
)
}
export default App
演示