我最近开始学习React,并试图让我的简单应用程序正常运行。
我有主要的App组件:
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<header>
<h1>Test</h1>
</header>
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1" aria-expanded="false">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</div>
<div className="collapse navbar-collapse" id="navbar-collapse-1">
<ul className="nav navbar-nav">
<li><NavLink to="/vehiclemakes">Vehicle Makes</NavLink></li>
</ul>
</div>
</div>
</nav>
<div className="container">
<Route path="/vehiclemakes" component={VehicleMakes}/>
</div>
</div>
</BrowserRouter>
);
}
}
正如你所看到我使用路由并在我的导航栏中我有一个指向Vehicle Makes组件的链接,该组件应该通过api调用来获取带有车辆的表格:
let vehicleMakes = [];
class VehicleMakes extends React.Component{
componentDidMount(){
Axios.get(`http://localhost:15163/api/vehiclemakes`)
.then((result) => {
const vehicleMakesData = result;
vehicleMakes = vehicleMakesData.data.data;
})
}
render(){
return(
<div>
<VehicleMakesTable vehicleMakes={vehicleMakes} />
</div>
);
}
}
VehicleMakesTable组件呈现VehicleMakesTableHeader和VehicleMakesTableRow组件:
class VehicleMakesTable extends React.Component{
render(){
console.log("table");
const rows = [];
this.props.vehicleMakes.forEach((vehicleMake) => {
rows.push(
<VehicleMakesTableRow
vehicleMake={vehicleMake}
key={vehicleMake.id} />
);
});
return(
<table>
<thead>
<VehicleMakesTableHeader />
</thead>
<tbody>{rows}</tbody>
</table>
);
}
}
class VehicleMakesTableHeader extends React.Component{
render(){
return(
<tr>
<th>Name</th>
</tr>
);
}
}
class VehicleMakesTableRow extends React.Component{
render(){
const vehicleMake = this.props.vehicleMake;
return(
<tr>
<td>{vehicleMake.name}</td>
</tr>
);
}
}
我遇到的问题是,当我在主App组件中单击Vehicle Makes链接时,在初始加载时,我的表被渲染但没有任何行。所以&#34; VehicleMakesTableHeader&#34;组件被渲染,但&#34; VehicleMakesTableRow&#34;组件没有。当我再次点击链接(第二次)然后&#34; VehicleMakesTableRow&#34;组件也会被渲染。
我不知道我做错了什么,为什么我必须点击两次链接才能正确呈现表格?
答案 0 :(得分:0)
您需要将vehicleMakes
存储在状态中,以便在componentDidMount
更新时触发重新呈现:
class VehicleMakes ... {
state = { vehicleMakes: [] }
...
.then(result => this.setState({ vehicleMakes: result.data.data }));
...
<VehicleMakesTable vehicleMakes={this.state.vehicleMakes} />
答案 1 :(得分:0)
问题在于:
Vehicle
您将A >: Bicycle <: Vehicle
保留为常规变量。 React没有收到有关此变量的任何更改的通知,也不会重新呈现。这就是为什么你有像react state
这样的东西。每次let vehicleMakes = [];
class VehicleMakes extends React.Component{
componentDidMount(){
Axios.get(`http://localhost:15163/api/vehiclemakes`)
.then((result) => {
const vehicleMakesData = result;
vehicleMakes = vehicleMakesData.data.data;
})
}
render(){
return(
<div>
<VehicleMakesTable vehicleMakes={vehicleMakes} />
</div>
);
}
}
更改时 - 会通知反应状态已更改并重新呈现。修正:
vehicleMakes