- 浏览: 2551957 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
ReactJS(2)Components State and Lifecycle
ENV
>node --version && npm --version
v8.0.0
5.0.0
Extracting Components
It is great idea to split the components.
function formatDate(date) {
return date.toLocaleDateString();
}
function Avatar(props) {
return (
<img className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name} />
);
}
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">
{props.user.name}
</div>
</div>
);
}
function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'http://placekitten.com/g/64/64'
}
};
ReactDOM.render(
<Comment
date={comment.date}
text={comment.text}
author={comment.author} />,
document.getElementById('root')
);
Props are Read-Only
All React components must act like pure functions with respect to their props.
State and Lifecycle
State is similar to props, it is private and fully controlled by the component. Local state is exactly a feature available only to classes.
Converting a Function to a Class
1 Create an ES6 class with the same name that extends React.Component.
2 Add a single empty method to it called render()
3 Move the body of the function into the render()
4 Replace props to this.props
class Clock extends React.Component {
render() {
return (
<div> … </div>
)
}
}
Adding Local State to a Class
1 Replace this.props.date with this.state.date in render()
2 Add a class contractor that assign the initial this.state
3 Remove the date prop from the <Clock /> element
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>
);
}
}
Adding Lifecycle Methods to a Class
mounting and unmounting in React
The method componentDidMount() hook runs after the component output has been rendered to the DOM.
We render DOM only once, but every time when we call tick(), it will change the state value in render.
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')
);
Using State Correctly
1 Do Not Modify State Directly
this.state.comment = “hello”; //Wrong
this.setState({comment:’Hello'});
The only place where we can assign this.state is the constructor
2 State Updates May Be Asynchronous
second format of setState method
this.setState(function(prevState, props){
return {
counter: prevState.counter + props.increment
};
});
3 State Updates are Merged
constructor(props) { super(props); this.state = { posts: [], comments: [] }; }
componentDidMount() {
fetchPosts().then(response => { this.setState({ posts: response.posts }); });
fetchComments().then(response => { this.setState({ comments: response.comments }); });
}
we can call this.setState multiple times, it will merge itself.
Data Flow
function App() {
return ( <div> <Clock /> <Clock /> <Clock /> </div> );
}
ReactDOM.render( <App />, document.getElementById('root'));
Each Clock sets up its own timer and updates independently.
References:
https://facebook.github.io/react/docs/components-and-props.html
https://facebook.github.io/react/docs/state-and-lifecycle.html
ENV
>node --version && npm --version
v8.0.0
5.0.0
Extracting Components
It is great idea to split the components.
function formatDate(date) {
return date.toLocaleDateString();
}
function Avatar(props) {
return (
<img className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name} />
);
}
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">
{props.user.name}
</div>
</div>
);
}
function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'http://placekitten.com/g/64/64'
}
};
ReactDOM.render(
<Comment
date={comment.date}
text={comment.text}
author={comment.author} />,
document.getElementById('root')
);
Props are Read-Only
All React components must act like pure functions with respect to their props.
State and Lifecycle
State is similar to props, it is private and fully controlled by the component. Local state is exactly a feature available only to classes.
Converting a Function to a Class
1 Create an ES6 class with the same name that extends React.Component.
2 Add a single empty method to it called render()
3 Move the body of the function into the render()
4 Replace props to this.props
class Clock extends React.Component {
render() {
return (
<div> … </div>
)
}
}
Adding Local State to a Class
1 Replace this.props.date with this.state.date in render()
2 Add a class contractor that assign the initial this.state
3 Remove the date prop from the <Clock /> element
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>
);
}
}
Adding Lifecycle Methods to a Class
mounting and unmounting in React
The method componentDidMount() hook runs after the component output has been rendered to the DOM.
We render DOM only once, but every time when we call tick(), it will change the state value in render.
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')
);
Using State Correctly
1 Do Not Modify State Directly
this.state.comment = “hello”; //Wrong
this.setState({comment:’Hello'});
The only place where we can assign this.state is the constructor
2 State Updates May Be Asynchronous
second format of setState method
this.setState(function(prevState, props){
return {
counter: prevState.counter + props.increment
};
});
3 State Updates are Merged
constructor(props) { super(props); this.state = { posts: [], comments: [] }; }
componentDidMount() {
fetchPosts().then(response => { this.setState({ posts: response.posts }); });
fetchComments().then(response => { this.setState({ comments: response.comments }); });
}
we can call this.setState multiple times, it will merge itself.
Data Flow
function App() {
return ( <div> <Clock /> <Clock /> <Clock /> </div> );
}
ReactDOM.render( <App />, document.getElementById('root'));
Each Clock sets up its own timer and updates independently.
References:
https://facebook.github.io/react/docs/components-and-props.html
https://facebook.github.io/react/docs/state-and-lifecycle.html
发表评论
-
MongoDB 2019(3)Security and Auth
2019-11-16 06:48 241MongoDB 2019(3)Security and Aut ... -
Memory Leak in NodeJS
2018-12-20 06:26 736Memory Leak in NodeJS I have d ... -
Remote Desktop Client
2018-12-07 13:19 1200Remote Desktop Client There is ... -
MetaBase UI Console(2)Docker on MySQL
2018-11-29 06:58 944MetaBase UI Console(2)Docker on ... -
AWS Lambda and Serverless Timeout
2018-09-20 01:20 629AWS Lambda and Serverless Timeo ... -
2018 WebSocket(1)Introduction
2018-03-20 01:22 11102018 WebSocket(1)Introduction ... -
2018 TypeScript Update(3)Introduction Basic Grammar
2018-03-08 03:08 6092018 TypeScript Update(3)Introd ... -
2018 TypeScript Update(2)Introduction Basic Grammar - Classes and Functions
2018-03-06 05:32 5572018 TypeScript Update(2)Introd ... -
2018 TypeScript Update(1)Introduction Basic Grammar - Types and Interface
2018-03-03 01:15 6052018 TypeScript Update(1)Introd ... -
Charts and Console(6)Paging
2018-03-01 00:12 586Charts and Console(6)Paging Th ... -
Vue.JS(3)Google Login
2018-02-14 04:53 1317Vue.JS(3)Google Login I just p ... -
Vue.JS(2)Monitor Water Console - ChartJS and Axios
2018-02-14 03:17 726Vue.JS(2)Monitor Water Console ... -
Vue.JS(1)Introduction and Basic Demo
2018-02-08 06:47 615Vue.JS(1)Introduction and Basic ... -
Charts and Console(5)Validation Form
2017-10-03 05:12 811Charts and Console(5)Validation ... -
Charts and Console(4)Display and Enhancement
2017-09-20 05:39 639Charts and Console(4)Display an ... -
Charts and Console(3)Auth and Login
2017-09-13 03:45 667Charts and Console(3)Auth and L ... -
Charts and Console(2)Login and Proxy
2017-08-31 05:39 878Charts and Console(2)Login and ... -
Charts and Console(1)UI Console and RESTful Client
2017-08-29 11:02 771Charts and Console(1)UI Console ... -
Blog Project(2)Express Backend API - istanbul - mocha - bunyan
2017-06-09 00:05 485Blog Project(2)Express Backend ... -
ReactJS(5)Composition vs Inheritance
2017-06-06 05:55 1117ReactJS(5)Composition vs Inheri ...
相关推荐
7. **1.nested components.html** 和 **2.states.html**:嵌套组件是React中常见的情形,文件1可能讲解如何创建和使用嵌套组件,而文件2则会深入讨论组件的状态(state),它是组件内部可变的数据,通过`this....
2. **State and Props**:在React中,组件的状态(state)是可以改变的,而属性(props)是只读的。当state变化时,组件会自动重新渲染。在这个计时器应用中,状态可能包含当前的计时值、是否正在计时、是否需要暂停...
2. **Props and State**: 组件可以接收外部数据作为props(属性),并使用state(状态)来管理内部数据。Props是只读的,由父组件传递;而state是可以改变的,通常用于管理组件的动态数据。 3. **Lifecycle Methods...
4. **State and Lifecycle**: 学习如何管理组件的状态(state)以及生命周期方法。状态是组件可以改变的数据,而生命周期方法允许我们在特定时刻执行代码,如组件加载时、更新时或卸载时。 5. **React Hooks**: ...
3. **State and Props**:组件的状态(state)和属性(props)是React数据流的核心。学员需要学会何时使用状态,如何通过props传递数据,以及如何响应props和状态的变化。 4. **Lifecycle Methods**:React组件有...
4. **生命周期方法(Lifecycle Methods)**:React组件有不同的生命周期阶段,每个阶段都有特定的方法可以调用,如render、componentDidMount、componentDidUpdate等。这些方法帮助开发者在特定时间点执行操作。 5....
React Repo其中63526 843 2-56837 263 27736259 56837帮助了我React中的片段: <> </>ReactJsVS。 节点JS ReactJS:客户端/前端====> API使用者/客户NodeJS:服务器端/后端====> API Exposer /厨房API:沟通器...
5. **lifecycle-methods** - 可能展示了不同生命周期方法的用法,如`componentDidMount`, `shouldComponentUpdate`, `componentDidUpdate`等。 6. **examples** 或 **exercises** 文件夹 - 提供了实际操作的例子,...
2. **状态(State)**:组件的状态是其内部数据,可以驱动组件的视图更新。在`AddGame`组件中,状态可能包含用户输入的游戏名,当用户提交时,状态会被更新,并触发组件重新渲染。 3. **props(Properties)**:...
2. **components** 文件夹(如果存在):这里会存储自定义的React组件。每个组件通常有自己的独立文件,命名遵循驼峰式命名规则,如`MyComponent.js`。 3. **styles** 文件夹(如果存在):存放CSS或CSS-in-JS样式...
2. **状态管理(State Management)**:React组件有自己的状态(state),状态驱动组件的视图更新。对于更复杂的全局状态管理,项目可能会使用Redux、MobX或其他类似的库。 3. **属性(Props)**:组件之间的通信...
4. **Lifecycle Methods**:React组件有其生命周期方法,如`componentDidMount`、`shouldComponentUpdate`和`componentDidUpdate`等,这些方法在组件的不同阶段被调用,用于执行特定任务。 5. **Hooks**:React ...
4. **生命周期方法(Lifecycle Methods)**:React组件有多个生命周期方法,如`componentDidMount`、`shouldComponentUpdate`和`componentDidUpdate`,这些方法在组件的不同阶段被调用,帮助开发者控制组件的行为。...
3. **State and Props**:组件的状态(state)和属性(props)是React中数据管理的关键概念。状态是组件可以改变的数据,而props是从父组件传递给子组件的数据。 4. **Lifecycle Methods**:组件生命周期方法,如`...
1. **ReactJS**: React是Facebook开源的一款JavaScript库,用于构建用户界面,尤其是单页应用程序(SPA)。它强调使用组件化的开发方式,将UI拆分为独立可复用的部分。在Task-Tracker中,每个任务项、任务列表或者...