我是React JS的新手,正在尝试实现类似于Angular示例应用程序的东西。
我有一个客户表,希望在表底部看到所选客户。
我用react-router-dom尝试了以下操作:
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import 'bootstrap/dist/css/bootstrap.css';
ReactDOM.render((<BrowserRouter><App /></BrowserRouter>), document.getElementById('root'));
registerServiceWorker();
// App.js
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
import Customers from './components/customers';
import Customer from './components/customer';
export default class App extends Component {
state = {
};
render() {
return (
<React.Fragment>
<Customers />
<Route path={`/customer/:id`} component={Customer} />
</React.Fragment>
);
}
}
// customers.jsx
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Customers extends Component {
state = {
customers: []
};
render() {
return (
<React.Fragment>
<header className="jumbotron"><h1>Customer List</h1></header>
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{this.state.customers.map(c => (<tr key={c.id}><td><Link to={`/customer/${c.id}`}>{c.name}</Link></td><td>{c.address}</td></tr>))}
</tbody>
</table>
<hr />
</div>
<footer className="footer">© 2018</footer>
</React.Fragment>
);
}
async componentDidMount() {
const result = await fetch('http://api.com/customers');
const customers = await result.json();
this.setState({ customers });
console.log(this.state.customers);
}
}
// customer.jsx
import React, { Component } from 'react';
export default class Customer extends Component {
render() {
return (<p>Customer</p>);
};
}
App.js中添加路由的行(路由路径= {{/customer/:id
}组件= {Customer})引起了该错误。如果删除该行,我可以看到客户列表,但是一旦添加此行,我就会收到该错误消息。
我是否错过了有关此路由器工作方式的信息?
谢谢。
更新
将App.js更改为这个非常简单的版本会导致错误
import React, { Component } from 'react';
import { Route } from 'react-router-dom/Route';
export default class App extends Component {
state = {
};
render() {
return (
<div>
<Route exact path='/' render={() => (<h1>Hello</h1>)} />
<Route exact path='/customer' render={() => (<h1>Customer</h1>)} />
</div>
);
}
}
完整的错误消息是:
元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记了从定义文件中导出组件,或者可能混淆了默认导入和命名导入。
答案 0 :(得分:1)
更改此内容:
import {Route} from "react-router-dom/Route";
对此:
import Route from "react-router-dom/Route";
路由是直接导出时的默认导出:"react-router-dom/Route"
从基本包中导入Route
时,可以使用命名导出
import {Route} from "react-router-dom";
但是不要将两者混在一起。
答案 1 :(得分:0)
好像您在Customer
组件的render()
方法中存在语法错误,当您尝试使用/呈现此方法时,这会引起问题。
尝试以下修复程序:
export default class Customer extends Component {
render() {
return (<p> Customer</p>); // <-- remove the whitespace in
// closing tag </p> like so
};
}