刚开始使用React,我已经显示了已创建的用户列表。我的用户列表当前显示在http://127.0.0.1:8000/上,我想在另一个URL示例http://127.0.0.1:8000/users中进行设置。我已经阅读了文档,但尝试了许多替代方法后仍无法弄清楚。这是我的代码:
Users.js
import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getUsers } from '../../actions/users';
export class Users extends Component {
static propTypes = {
users: PropTypes.array.isRequired
};
componentDidMount() {
this.props.getUsers();
}
render() {
return (
<Fragment>
<h2>Users</h2>
<table className="table table-striped">
<thead>
<tr>
<th>id</th>
<th>username</th>
<th>first_name</th>
<th>last_name</th>
<th />
</tr>
</thead>
<tbody>
{this.props.users.map(user => (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.username}</td>
<td>{user.first_name}</td>
<td>{user.last_name}</td>
</tr>
))}
</tbody>
</table>
</Fragment>
);
}
}
const mapStateToProps = state => ({
users: state.users.users
});
export default connect(mapStateToProps, { getUsers })(Users);
Dashboard.js
import React, { Fragment } from 'react';
import Form from './Form';
import Users from './Users';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
export default function Dashboard() {
return (
<Fragment>
<Users/>
</Fragment>
);
}
App.js
import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";
import Header from "./layout/Header";
import Dashboard from "./users/Dashboard";
import { Provider } from 'react-redux';
import store from '../store';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
class App extends Component {
render() {
return (
<Provider store={store}>
<Fragment>
<Header />
<div className="container">
<Dashboard />
</div>
</Fragment>
</Provider>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
答案 0 :(得分:0)
检查React-Router的概念,这应该可以帮助您实现所需的目标
问候 帕万·巴米迪帕蒂(Pavan Bhamidipati)
答案 1 :(得分:0)
只需使用路由器
import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";
import Header from "./layout/Header";
import Users from "./users/Users"; //Users component location
import { Provider } from 'react-redux';
import store from '../store';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<Header />
<Route exact path="/users" component={Users} />
</Router>
</Provider>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));