我正在尝试重用组件以从mysql渲染表视图。我有一个查询生成的导航,该查询列出了数据库中的所有表。
import React, { Component } from 'react';
import { BrowserRouter as Router, NavLink } from "react-router-dom";
import './navigation.scss';
class Navigation extends Component {
state = {
items: []
}
Normalize = name => {
return name.split('_')
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ');
}
componentDidMount() {
fetch('http://localhost:3132/api/tables')
.then(data => {
return data.json();
})
.then(json => {
let tables = json.map((table, index) => {
var name = table.table_name;
return <li key={index}>
<NavLink activeClassName="active-nav" to={'/table/' + name} name={name}>{this.Normalize(name)}</NavLink>
</li>;
})
this.setState({ tables: tables });
});
}
render() {
return (
<div className="navigation">
<h2>Tables</h2>
<Router>
<ul>
<li><NavLink exact activeClassName="active-nav" to="/">Home</NavLink></li>
{this.state.tables}
</ul>
</Router>
</div>
)
}
}
export default Navigation;
链接的工作方式是更新URL,并分配活动类。但是,“视图”组件在初始页面加载后永远不会更改。
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from './components/home/home.component';
import Table from './components/table/table.component';
const Routes = () => {
return (
<div className="main">
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path={"/table/:path"} component={(props) => (<Table {...props} />)}></Route>
</Switch>
</div>
)
}
export default Routes;
即使静态“本地”路由处于活动状态也不会更新。这是Table组件的外观:
import React, { Component } from 'react';
class Table extends Component {
state = {};
componentDidMount() {
this.setState({tableName: this.props.match.params.path});
}
render() {
return <h1>{this.state.tableName}</h1>
}
}
export default Table;
我该怎么做才能使“表格”组件呈现/更新?
编辑: 尝试了评论中建议的功能组件,因此没有运气
import React, { Component } from 'react';
const Table = props => {
return <h1>{props.match.params.path}</h1>
}
export default Table;