从零开始搭建一个react项目开发(4)

在ToDoApp中我们可以使用许多生命周期方法的钩子, 其中一个就是componentWillMount。 这个方法的执行是在页面加载并且render方法之前。可以在其中获取列表数据,在我们的APP中直接用一个虚拟的数组提供。(值得注意的是componentWillMount会引起很多小问题,因此真实项目中尽量不要使用,而是应该用componentDidMount)。

在 ToDoApp中 render 方法之前添加:

  componentWillMount(){ // run before the render method
   this.setState({ // add an array of strings to state.
    list: ['thing1', 'thing2', 'thing3']
   })
  };

现在我们获取了一个虚拟列表,需要重点注意的就是react依赖于state和props,只有当state和props改变的时候react组件才会刷新。

现在我们添加列表到这个view里,这里不是直接简单的在里面修改jsx,而是再创建一个新的组件来构建列表,这次我们学习使用函数型组件,需要注意的是函数型组件没有生命周期方法和state属性,它仅仅是一个返回jsx的函数,并且参数是props。

那么props到底是什么呢?props是从父组件传递进子组件的数据的名字,这是一个很重要的概念,也是react app数据传递的最典型与最推荐的方法。通常我们将数据保持在app的顶端组件,通过组件让数据流下来保证APP的精确运行。这些数据和props的一些处理可能会影响APP的运行,但是假如你按照这个课程的实践流程来做,这些影响都会很小。

再新建一个components文件夹并在其中新建一个List.js作为我们要创建的函数型组件。用const来新建一个函数,参数名字写作props。

函数形式如下所示:

 const List = (props) => { // we're using an arrow function and const variable type, a ES6 features

  return (
   <div>
    I'm a list!!!
   </div>
  )
 };

 export default List;

在 ToDoApp.js引入 List用List 组件替换 List goes here.,写法为 <List />.现在在浏览器中就可以看到"I'm a list!!!"

现在我们来把这个变成真实的列表,首先就需要通过props传递数据,我们把这个从state中获取的数据list通过命名为listItems的props传递,写作: <List listItems={this.state.list} /> ,现在 List 已经通过props获取了 ToDoApp中的数据。

然后在 List 组件中我们需要render一个列表,先用下面的jsx代码代替:

<div>
 <ul>
  {
   list // this is a variable we'll define next
  }
 </ul>
</div>

注意这个大括号,js可以在这里面执行并将返回添加到view里。首先我们定义一个列表变量:

const list = props.listItems.map((el, i)=>(
 // All where doing here is getting the items listItems prop
 // (which is stored in the state of the parent component)
 // which is an array, and we're running the .map method
 // which returns a new array of list items. The key attribute is
 // required, and must be unique.
 <li key={i}><h2>el</h2></li>
));

      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/205.html