文档章节

State Management in React Apps - Part I

Kolosek
 Kolosek
发布于 2018/06/05 14:23
字数 621
阅读 16
ReactJS">收藏 0

Previously we have learnt how to properly use JSX, and how React components communicate with each other. Yet, we still didn't cover another very important question: where to store information that our application cares about. Today we're talking about application state management in React.

There are a lot of ways to handle application state but first, we'll take a look at the simplest one - components' state.

ReactJS is awesome!

React Components' State

You might have previously seen this.state. A component has its' local state, an object with a purpose to keep information important to the component, like that movie list you were supposed to render. This local state is firstly initialized in the constructor, like this:

constructor() {
    super();
    this.state = {
        itemKey: defaultItemValue,
        ...
    };
}

Keep in mind that you should define a default value for each of the state attributes you will use in the component, even if the initial value is undefined.

What should I store in components' state? There is a debate on when to use components' state, and when to move to a bit more advanced approach: many developers in the past were forcing the philosophy that you shouldn't use this.state at all, but you should keep everything in the globally accessible state (i.e. redux state - which will be mentioned a bit later), even if it's just a simple toggle used for conditional rendering.

However, there is no point in keeping a value in the redux state if it is only used inside this one component; and if the application that is being developed is pretty simple, there's no need to introduce yet another dependency like a separate library for state management. In the beginning, when learning React, it's better to stick to using this.state, as it doesn't require diving into yet another library.

React components' state is asynchronously updated. You will use this.setState function to update your state. However, there is a thing to always keep in mind: you shouldn't use setState two times in a row when one setState depends on the previous one, due to its' asynchronous nature.

// assuming this.state.count === 0
this.setState({
    count: this.state.count + 1
});
this.setState({
    count: this.state.count + 1
});
// it doesn't necessarily mean that this.state.count will be 2 now

However, you can use so called functional setState for setting the state dependent on previous state or on some of components' props:

this.setState((previousState, currentProps) => {
    return {
        count: previousState.count + 1,
    };
});

Using functional setState is the best way to use setState.
If you want to change multiple values kept in the state, you don't need to call setState multiple times:

// "standard" way
this.setState({
    item1: value1,
    item2: value2,
});
// "functional" way 
this.setState((previousState, currentProps) => {
    return {
        item1: value1,
        item2: value2,
    };
});

The state shouldn't be mutated. This applies both to simple components' state and some bit more advanced ones, like third-party redux state. Components' state should only be changed by using setState function. While you can just use this.state.disabled = true, it won't trigger rerendering of the component. There is no prevention of mutating items kept in the state, so you have to care about not mutating them yourself.

So far we've covered React components' state and its' three basic concepts: it's immutableasynchronous and local. It is a quick way to handle storing information in simple apps, but also for local variables that should be accessed from multiple places inside a components' instance, even in really big and complex applications.

However, for more complex applications, for components that are too dependent on each others' state, and for better handling of the data used by an application, there are third-party libraries like Redux, Flux, CerebralJS and many other, which provide more advanced ways to handle app state. We'll talk more about these next time.

This article is originally published on Kolosek Blog.

© 著作权归作者所有

Kolosek
粉丝 0
博文 29
码字总数 20461
作品 0
塞尔维亚
CEO
私信 提问
Game Programming using JavaScript, React, Canvas2D and CSS – Part 2

In the last post, we set up our react-app, added an class to handle user input and added a first component to render a title-screen. In this part, we will implement state manage......

Philipp_Engelmann
2017/12/22
0
0
使用React Hook实现Redux状态机

Redux is a predictable state container for JavaScript apps. 原文地址:使用React Hook实现Redux状态机 本文的代码可以在CodeSandbox中查看。 Redux是React经常用到的一个数据状态管理器(...

xiangjun
09/13
0
0
django 报错求大神指教

django执行python manage.py migrate后出现报错 Operations to perform: Synchronize unmigrated apps: staticfiles, messages Apply all migrations: sessions, admin, auth, contenttypes,......

迷途小书虫
2017/03/10
328
4
这一次彻底搞定useReducer-使用篇

useReducer-基础概念篇 useReducer-使用篇 useReducer-配合useContext使用 我们在第一篇文章中介绍了JavaScript中的reducer以及他的一些特点,对reducer不熟悉的小伙伴可以先看看第一篇。 Re...

人人贷大前端技术中心
06/17
0
0
Game Programming using JavaScript, React, Canvas2D and CSS – Part 1

In this series, I want to show you how to create simple 2D games using JavaScript, React, Canvas and CSS. We will make a simple Space Invaders clone, you can check out the end r......

Philipp_Engelmann
2017/12/22
0
0

没有更多内容

加载失败,请刷新页面

加载更多

一次看懂 Https 证书认证

TLS > 传输层安全性协定 TLS(Transport Layer Security),及其前身安全套接层 SSL(Secure Sockets Layer)是一种安全协议,目的是为网际网路通信,提供安全及数据完整性保障。 如图,TLS...

极客收藏夹
20分钟前
3
0
https证书买哪家好?有哪些供应商

在选购https证书前除了要了解类型外,还需要了解https证书供应商,毕竟不同的供应商,提供的产品质量与服务也是有差异的。今天小编就为大家讲讲https证书供应商方面的内容,希望各位会喜欢。...

安信证书
21分钟前
4
0
Zuul 配置

概述:zuul底层是基于servlet,是由一系列的filter链构成。 1、路由配置 a、单例serverId映射 zuul: routes: client-a: path: /client/** serviceId: client-a 意思是...

java框架开发者
39分钟前
3
0
zk中FinalRequestProcessor解析

是处理器最后一个环节 FinalRequestProcessor implements RequestProcessor 处理器链最后一个环节处理事务和非事务请求最后一个环节 构造器 public FinalRequestProcessor(ZooKeeperServer z...

writeademo
39分钟前
3
0
Axios 详解

首先祝广大程序猿们节日快乐! 一、axios简介 基于promise,用于浏览器和node.js的http客户端 二、特点 支持浏览器和 node.js 支持 promise 能拦截请求和响应 能转换请求和响应数据 能取消请求...

张兴华ZHero
40分钟前
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部