使用 redux-thunk 时候由于一个请求需要写三个 action, 比较麻烦. redux-promise-middleware 可以在根据 type 自动生成对应的 action, 一个例子如下
action 只需写一个基本的, 对应会生成: FETCH_DATA_PENDING
, FETCH_DATA_SUCCESS
, FETCH_DATA_REJECTED
三种形式
// action
export const getData = () => {
#enables colorin the terminal bash shell export | |
export CLICOLOR=1 | |
#setsup thecolor scheme for list export | |
export LSCOLORS=gxfxcxdxbxegedabagacad | |
# lambda prompt | |
export PS1="\[\e[0;35m\]λ\[\e[m\] \[\e[33;40m\]\@\[\e[m\] \[\e[0;32m\]\W \[\e[m\]" | |
#sets up theprompt color (currently a green similar to linux terminal) |
import { createStore, applyMiddleware } from 'redux' | |
import thunk from 'redux-thunk' | |
import axios from 'axios' | |
// 建立一个 local state 负责 loading | |
const state = { | |
loading: false | |
} | |
// 这个 action 用于在下面的 fetchUser 里面 dispatch |
重点:
示例 1, 非闭包:
// 无论调用多少次 fakeCounter(), 永远返回的是 0
const fakeCounter = function() {
import React, { useState } from 'react' | |
import ReactDOM from 'react-dom' | |
const text = 'To see the answers, we need to take a step back. The goal of this article isn’t to give you a list of bullet point recipes. It’s to help you truly “grok” useEffect. There won’t be much to learn. In fact, we’ll spend most of our time unlearning.' | |
const RevealText = props => { | |
const { text, maxLength } = props | |
const [hidden, setHidden] = useState(true) | |
if (text.length <= maxLength) { |
1
面向对象编程的问题是,每个对象都有自己的状态,开发程序时,必须记住当前所有对象的状态。
为了让我们的生活更轻松,最好只有一小部分代码库处理状态,其他代码都是无状态和纯的。实际上,这就是前端的 Redux 库取得巨大成功的主要原因。
2 React 应该尽量遵守 "有状态的组件没有渲染, 有渲染的组件没有状态" 这一原则, 这句话的意思是:
const useFormInput = initialValue => { | |
const [value, setValue] = useState(initialValue) | |
const handleChange = e => { | |
setValue(e.target.value) | |
} | |
return { | |
value, | |
onChange: handleChange |
/* | |
使用 react-redux 实现的计数器 | |
*/ | |
import React from 'react' | |
import ReactDOM from 'react-dom' | |
import { connect, Provider } from 'react-redux' | |
import { createStore } from 'redux' | |
const mapStateToProps = state => { |