目录
1.Redux
本文引用了,这篇掘金文章,这篇文章写的挺好的,b站也有她的视频!
2.Mobx
3.Recoil
1)RecoilRoot
如果组件中使用Recoil
,则可以将RecoilRoot
放置在父组件的某个位置。最好将其放在根组件中
。
2)Atom
一个atom
代表一个状态
。atom可在任意组件中进行读写。读取atom值的组件隐式订阅了该atom,因此任何atom的更新都将导致该atom的组件重新渲染。
3)Selector
selector
代表一个派生状态
,派生状态时状态的转换
。你可以将派生状态视为将状态传递给以某种方式修改给定状态的纯函数的输出。
4)常用的recoil的hook函数
(1)useRecoilState
当组件同时需要读写状态时,推荐使用该hook。
(2)useRecoilValue
当一个组件需要在不写入state的情况下读取state时,推荐使用该hook。
(3)useSetRecoilState
返回一个setter函数,用来更新可写Recoil state的值,状态变化不会导致组件重新渲染。
当一个组件需要写入而不需要读取state时,推荐使用此hook。
如果组件使用了useRecoilState()
来获取setter函数
,那么同时它也会订阅更新,并在atom
或selector
更新时重新渲染。使用useSetRecoilState()
允许组件在值发生改变时而不用给组件订阅重新渲染的情况下设置值。
5)关于recoil的例子
(1)输入框
src文件夹
下的app.js
import {RecoilRoot} from "recoil";
import HomePage from "./pages/HomePage";
export default function App(props) {
return (
<div className="App">
<RecoilRoot>
<HomePage />
</RecoilRoot>
</div>
);
}
其中store文件夹
和pages文件夹
在src文件夹
下
store文件夹
下的index.js
//状态atom,在需要的组件中,直接引入并使用useRecoilState()即可。
import {atom,selector} from "recoil";
export const textState = atom({
key: 'textState', //全局下保持唯一性
default: '', //初始值
});
//派生状态,在需要的组件中,可以使用useRecoilValue()的hook,
//来读取派生状态即可。
export const charCountState = selector({
key: "charCountState", //全局下唯一性
get: ({get}) => {
const text = get(textState);
return text.length;
}
});
pages文件夹
下的HomePage
组件
import {useRecoilState, useRecoilValue, useSetRecoilState} from "recoil";
import {textState, charCountState} from "../store/";
import TextInput from "./TextInput.js";
import CharacterCount from "./CharacterCount.js";
export default function HomePage(props) {
return (
<div>
<h3>HomePage</h3>
<TextInput/>
<CharacterCount/>
</div>
);
}
pages文件夹
下的TextInput
组件
import {useRecoilState} from "recoil";
import {textState, charCountState} from "../store/";
export function TextInput(props) {
const [text, setText] = useRecoilState(textState);
const onChange = e => {
setText(e.target.value);
};
return (
<div>
<input type="text" value={text} onChange={onChange}/>
<br/>
Echo:{text}
<div>
);
}
pages文件夹
下的CharacterCount
组件
import {useRecoilValue} from "recoil";
import {textState, charCountState} from "../store/";
export function CharacterCount(props){
const count = useRecoilValue(charCountState);
return (
<div>
<p>{count}</p>
<div>
);
}
(2)todolist清单
4.对比redux,mobx,recoil
redux
是集中式管理state
,而recoil
和mobx
是分散式的recoil
目前只适用于hooks函数recoil
时facebook开发的,可以使用react内部的调度机制,这是redux
和mobx
不支持的