React Native之React速学教程(中)
React Native之React速学教程(中)本文出自《React Native学习笔记》系列文章。 React Native是基于React的,在开发React Native过程中少不了的需要用到React方面的知识。虽然官方也有相应的Document,但篇幅比较多,学起来比较枯燥。 概述本篇为《React Native之React速学教程》的第二篇。本篇将从组件(Component)的详细说明、组件的生命周期(Component Lifecycle)、isMounted是个反模式等方面进行讲解,让大家对组件(Component)有个更系统以及更深入的认识。 组件的详细说明当通过调用 React.createClass() 来创建组件的时候,每个组件必须提供render方法,并且也可以包含其它的在这里描述的生命周期方法。 render
或者
React.DOM.div() ),也可以是自定义的复合组件。
你也可以返回 null 或者
false 来表明不需要渲染任何东西。实际上,React 渲染一个
<noscript> 标签来处理当前的差异检查逻辑。当返回
null 或者
false 的时候,
this.getDOMNode() 将返回
null 。
注意:
getInitialState
getDefaultProps
getDefaultProps() {
return {
title: '',popEnabled:true
};
},
注意
PropTypes
Usage: var NavigationBar=React.createClass({ propTypes: { navigator:React.PropTypes.object,leftButtonTitle: React.PropTypes.string,leftButtonIcon: Image.propTypes.source,popEnabled:React.PropTypes.bool,onLeftButtonClick: React.PropTypes.func,title:React.PropTypes.string,rightButtonTitle: React.PropTypes.string,rightButtonIcon:Image.propTypes.source,onRightButtonClick:React.PropTypes.func },
mixins
statics
var MyComponent = React.createClass({ statics: { customMethod: function(foo) { return foo === 'bar'; } },render: function() { } }); MyComponent.customMethod('bar'); // true 在这个块儿里面定义的方法都是静态的,你可以通过 displayName
isMounted
组件的生命周期(Component Lifecycle)在iOS中 那么在React 中组件(Component)也是有自己的生命周期方法的。 组件的生命周期分成三个状态:
Mounting(装载)
Updating (更新)
用此函数可以作为 react 在 prop 传入之后, render() 渲染之前更新 state 的机会。老的 props 可以通过 this.props 获取到。在该函数中调用 this.setState() 将不会引起第二次渲染。
该方法在初始化渲染的时候不会调用,在使用 forceUpdate 方法的时候也不会。如果确定新的 props 和 state 不会导致组件更新,则此处应该 返回 false。
在初始化渲染的时候该方法不会被调用。使用该方法做一些更新之前的准备工作。
该方法不会在初始化渲染的时候调用。使用该方法可以在组件更新之后操作 DOM 元素。 Unmounting(移除)
在该方法中执行任何必要的清理,比如无效的定时器,或者清除在 componentDidMount 中创建的 DOM 元素。 isMounted是个反模式isMounted通常用于避免修改一个已经被卸载的组件的状态,因为调用一个没有被装载的组件的 if(this.isMounted()) { //不推荐
this.setState({...});
}
上面做法有点反模式, React 在设计的时候通过 既然isMounted()是反模式,那么有没有可替代方案呢? class MyComponent extends React.Component {
componentDidMount() {
mydatastore.subscribe(this);
}
render() {
...
}
componentWillUnmount() {
mydatastore.unsubscribe(this);
}
}
使用可取消的Promise做异步操作。 const cancelablePromise = makeCancelable(
new Promise(r => component.setState({...}}))
);
cancelablePromise
.promise
.then(() => console.log('resolved'))
.catch((reason) => console.log('isCanceled',reason.isCanceled));
cancelablePromise.cancel(); // Cancel the promise
可取消的Promise。 const makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve,reject) => {
promise.then((val) =>
hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
);
promise.catch((error) =>
hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
return {
promise: wrappedPromise,cancel() {
hasCanceled_ = true;
},};
};
参考React’s official site About本文出自《React Native学习笔记》系列文章。 推荐阅读
推荐阅读
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |