前端框架React
来源:互联网 发布:记账软件中的红字 编辑:程序博客网 时间:2024/06/11 03:04
1.Introduction of state
the fact that theClock
sets up a timer and updates the UI every second should be an implementation detail of theClock
.事实上组件的功能和更新UI的代码应该是组件自己的具体实现细节。ReactDOM.render( <Clock />, document.getElementById('root'));为了实现上述的代码,我们需要为组件增加state。State is similar to props, but it is private and fully controlled by the component.State和props很相似,但是state是私有的,完全由组件控制。We mentioned before that components defined as classes have some additional features. Local state is exactly that: a feature available only to classes.state是一个只在class定义的组件里面才有的新特性。
2.将function转换成Class
Create an ES6 class with the same name that extends
React.Component
.Add a single empty method to it called
render()
.每一个Class类型的组件都要有一个render()方法。
Move the body of the function into the
render()
method.Replace
props
withthis.props
in therender()
body.在render()方法中,props要用this.props来代替
Delete the remaining empty function declaration.
class Clock extends React.Component { render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.props.date.toLocaleTimeString()}.</h2> </div> ); }}
3.给Class添加local state
我们将用下面的三步来完成date从props到state的过程:1.在render()方法中,用this.state.date来代替this.props.date
class Clock extends React.Component { render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); }}2.添加一个class的构造函数来初始化this.state,并且我们把props传进了基础的构造函数。class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); }}3.Remove thedate
prop from the<Clock />
elementclass Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); }}ReactDOM.render( <Clock />, document.getElementById('root'));
4.添加生命周期方法到Class中
We want to set up a timer whenever theClock
is rendered to the DOM for the first time. This is called "mounting" in React.我们希望给Class安装一个计时器,可以知道Class什么时候第一渲染到DOM里面。这在React叫做mountingWe also want to clear that timer whenever the DOM produced by theClock
is removed. This is called "unmounting" in React.我们也希望当这个Class的node被remove的时候能清除这个计时器。这叫做unmounting。这些方法叫做生命周期钩子。componentDidMount(){}这个钩子在组件输出被渲染到DOM之后run。这里set计时器很好。
componentWillUnmount(){}componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); }注意我们将timerID保存在this里面。Whilethis.props
is set up by React itself andthis.state
has a special meaning, you are free to add additional fields to the class manually if you need to store something that is not used for the visual output.尽管this.props由React自己设置,this.state有特殊的意义。我们可以添加其他的filed到class,只要我们需要存储的东西不会用在视觉输出里面。上面的翻译简直不是人话。意思是If you don't use something inrender()
, it shouldn't be in the state.如果我们需要保存的东西不会被用在render()方法中,也就是不会用在视觉输出中,那么这些东西就不应该被保存在state里面。Finally, we will implement the
tick()
method that runs every second.It will use
最后我们用this.setState()方法来更新组件本地的state。this.setState()
to schedule updates to the component local state:class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); }}ReactDOM.render( <Clock />, document.getElementById('root'));调用流程:1.When<Clock />
is passed toReactDOM.render()
, React calls the constructor of theClock
component. SinceClock
needs to display the current time, it initializesthis.state
with an object including the current time. We will later update this state.2. Reactthen calls theClock
component'srender()
method. This is how React learns what should be displayed on the screen. React then updates the DOM to match theClock
's render output.3.When theClock
output is inserted in the DOM, React calls thecomponentDidMount()
lifecycle hook. Inside it, theClock
component asks the browser to set up a timer to calltick()
once a second.4.Every second the browser calls thetick()
method. Inside it, theClock
component schedules a UI update by callingsetState()
with an object containing the current time. Thanks to thesetState()
call, React knows the state has changed, andcallsrender()
method again to learn what should be on the screen. This time,this.state.date
in therender()
method will be different, and so the render output will include the updated time. React updates the DOM accordingly.5.If theClock
component is ever removed from the DOM, React calls thecomponentWillUnmount()
lifecycle hook so the timer is stopped.
5.正确的使用State
1.不要直接改变state
// Wrongthis.state.comment = 'Hello';
我们要改变state,用setState这个方法// Correctthis.setState({comment: 'Hello'});The only place where you can assignthis.state
is the constructor.你唯一可以给this.state分配值的地方是构造函数。2.state的更新可能是异步的
react可能在一次更新中批处理多个setState方法。
3.state的更新会被合并Becausethis.props
andthis.state
may be updated asynchronously, you should not rely on their values for calculating the next state.因为更新可能是异步的,所以不要依赖他们的值来计算下一个state// Wrongthis.setState({ counter: this.state.counter + this.props.increment,});
To fix it, use a second form ofsetState()
that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:// Correctthis.setState((prevState, props) => ({ counter: prevState.counter + props.increment}));
When you callsetState()
, React merges the object you provide into the current state.react会合并你向state里面提供的对象。Then you can update them independently with separatesetState()
calls:componentDidMount() { fetchPosts().then(response => { this.setState({ posts: response.posts }); }); fetchComments().then(response => { this.setState({ comments: response.comments }); }); }
The merging is shallow, sothis.setState({comments})
leavesthis.state.posts
intact, but completely replacesthis.state.comments
.合并会不管this.state.posts,只会更新this.state.comments
6.The data flow down
Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn't care whether it is defined as a function or a class.parent和child控件都不会知道一个控件是stateful还是stateless。This is why state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it.除了这个控件本身,其他控件是不能access 这个控件的state的。A component may choose to pass its state down as props to its child components一个控件可以选择将它的state作为props传递给它的子控件。<h2>It is {this.state.date.toLocaleTimeString()}.</h2>This also works for user-defined components这同样适用于自定义组件。<FormattedDate date={this.state.date} />TheFormattedDate
component would receive thedate
in its props and wouldn't know whether it came from theClock
's state, from theClock
's props, or was typed by hand:这个组件会在它的props里面获得date,不会知道这个date来自Clock组件的state,来自Clock组件的props还是手动输入的。function FormattedDate(props) { return <h2>It is {props.date.toLocaleTimeString()}.</h2>;}
This is commonly called a "top-down" or "unidirectional" data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components "below" them in the tree.任何state都是被具体的state所拥有的。任何来自于那个state的数据或者UI只能影响低于这个state自己控件的控件。一个完整的例子:function FormattedDate(props) { return <h2>It is {props.date.toLocaleTimeString()}.</h2>;}class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return ( <div> <h1>Hello, world!</h1> <FormattedDate date={this.state.date} /> </div> ); }}function App() { return ( <div> <Clock /> <Clock /> <Clock /> </div> );}ReactDOM.render(<App />, document.getElementById('root'));
0 0
- 前端框架react研究
- [前端框架]React
- 前端框架React
- 前端框架React
- 前端框架React
- 前端框架React
- 前端框架React
- 颠覆式前端UI开发框架:React
- 颠覆式前端UI开发框架:React
- 颠覆式前端UI开发框架:React
- 前端框架React.js入门介绍
- 颠覆式前端UI开发框架:React
- 颠覆式前端UI开发框架:React
- 七周七种前端框架二: React 之概览
- 颠覆式前端UI开发框架:React
- 基于react+redux+webpack的前端框架
- 最火的一款前端框架----React
- 前端开发框架简介:angular和react
- SpringMVC的文件上传需要注意的问题
- Linux 下find指令
- Atitit 列出wifi热点以及连接
- 机器学习05-学习率与正规方程
- 机器学习入门系列01,Introduction 简介
- 前端框架React
- windows下的一个socket多人聊天程序(附源代码)
- SSH Exception 2017.3.26-1 java.lang.NullPointerException
- Linux中的粘滞位
- Git使用方法
- TensorFlow 实现深度神经网络 —— Denoising Autoencoder
- DOM事件
- Atitit 提升效率 界面gui方面的前后端分离与cbb体系建设 规范与推荐标准
- 第五周总结