您现在的位置:首页 >> 前端 >> 内容

【React全家桶入门之六】渲染用户列表

时间:2017/2/7 9:53:00 点击:

  核心提示:现在我们需要一个页面来展现数据库中记录的用户。在/src/pages下新建UserList.js文件。创建并导出UserList组件:import React from react;class Use...

现在我们需要一个页面来展现数据库中记录的用户。

在/src/pages下新建UserList.js文件。

创建并导出UserList组件

import React from 'react';

class UserList extends React.Component {

  render () {
    return (
      ...
    );
  }
}

export default UserList;

当页面加载的时候需要调用接口来获取用户列表,并把获取到的用户列表数据存放到组件的state中(this.state.userList):

class UserList extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      userList: []
    };
  }

  componentWillMount () {
    fetch('https://localhost:3000/user')
      .then(res => res.json())
      .then(res => {
        this.setState({
          userList: res
        });
      });
  }

  render () { ... }
}

在render方法中,使用数组的map方法将用户数据渲染为一个表格:

class UserList extends React.Component {
  constructor (props) { ... }

  componentWillMount () { ... }

  render () {
    const {userList} = this.state;

    return (
      

用户列表

{ userList.map((user) => { return ( ); }) }
用户ID 用户名 性别 年龄
{user.id} {user.name} {user.gender} {user.age}

); } }

在/src/index.js文件中添加指向这个页面的路由,并在/src/pages/Home.js中加入相应的链接:

// /src/index.js
import UserListPage from './pages/UserList';

ReactDOM.render((
  
    
    
    
  
), document.getElementById('app'));
// /src/pages/Home.js
class Home extends React.Component {
  render () {
    return (
      

Welcome

用户列表
添加用户

); } }

最后,我们可以在添加用户之后,使用this.context.router.push方法来跳转到用户列表页面:

// /src/pages/UserAdd.js
class UserAdd extends React.Component {
  handleSubmit (e) {
    ...

    fetch('https://localhost:3000/user', { ... })
      .then((res) => res.json())
      .then((res) => {
        if (res.id) {
          alert('添加用户成功');
          this.context.router.push('/user/list');
          return;
        } else {
          alert('添加失败');
        }
      })
      .catch((err) => console.error(err));
  }
  render () { ... }
}

// 必须给UserAdd定义一个包含router属性的contextTypes
// 使得组件中可以通过this.context.router来使用React Router提供的方法
UserAdd.contextTypes = {
  router: React.PropTypes.object.isRequired
};

这样我们在添加用户之后就可以立即在列表中看到最新添加的用户了:

【React全家桶入门之六】渲染用户列表

Tags:【R RE EA AC 
作者:网络 来源:一韬的React实验