简体   繁体   中英

Redirect to appropriate page while clicking on Button ReactJS/Django project

I'm new to the web development and chose django/Reactjs for my social network project.

I made a few api methods like account/view_user/ that returns list of users and account/view_user/ that returns attributes for particular user.

I also wrote a page in React that renders a list of users

class PersonnelContentFeed extends React.Component {
  constructor() {
    super();

    this.state = {
      'items': []
    }
  }
  componentDidMount() {
    this.getItems();
  }

  getItems() {
    fetch('http://localhost:8000/api/account/view_user/')
    .then(results => results.json())
    .then(results => this.setState({'items': results}));
  }

  render() {
    return (
      <ul>
        {this.state.items.map(function(item, index) {
          return <PersonnelContentItem item={item} key={index} />
        })}
      </ul>
    );
  }
}

class PersonnelContentItem extends React.Component {
  render() {
    return (
      <Row className="PersonnelContentItem">
        <Col xs="3"></Col>
        <Col xs="6">
          <Card>
            <CardImg top width="100%"></CardImg>
            <CardBody>
              <CardTitle>
                <strong>{this.props.item.first_name} {this.props.item.last_name}</strong>
              </CardTitle>
              <NavLink to='./PersonDetails'><Button>
                Details
              </Button>
              </NavLink>
            </CardBody>
          </Card>
        </Col>
      </Row>
    )
  }
}

There is also a React component for person details(similar to PersonnelContentFeed) The question is:

What should I do to redirect user to the appropriate details page (with right id, eg /api/account/view_user/1) while clicking "Details" Button.

Thank you all in advance.

Take a look at React Router URL Parameters. That's likely what you are looking for.

You can use the following routes to direct url path to the right component (view):

<Router>
  <Route exact path="/account/user-list" component={UserList} />
  <Route path='/account/user/:id' component={UserDetail} />
</Router>

This way you can pass the user's id as a parameter using the url.

You can see more examples in the React Router Docs:

https://reacttraining.com/react-router/web/example/url-params

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM