0
点赞
收藏
分享

微信扫一扫

react的状态管理库

whiteMu 2022-03-12 阅读 48

目录

1.Redux

本文引用了,这篇掘金文章,这篇文章写的挺好的,b站也有她的视频!

redux

2.Mobx

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函数,那么同时它也会订阅更新,并在atomselector更新时重新渲染。使用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,而recoilmobx是分散式的
  • recoil目前只适用于hooks函数
  • recoil时facebook开发的,可以使用react内部的调度机制,这是reduxmobx不支持的
举报

相关推荐

0 条评论