文档链接
使用 Recoil 会为你创建一个数据流向图,从 atom(共享状态)到 selector(纯函数),再流向 React 组件。Atom 是组件可以订阅的 state 单位。selector 可以同步或异步改变此 state。
安装
npm install recoil
全局配置
import React, { Component } from "react";
import { ConfigProvider } from 'antd';
import { withRouter } from "react-router-dom";
import { RecoilRoot } from 'recoil';
import Routes from "./router";
class App extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: false,
isAuthenticating: true
};
}
render() {
const childProps = {
isAuthenticated: this.state.isAuthenticated,
userHasAuthenticated: this.userHasAuthenticated
};
return (
<ConfigProvider>
<RecoilRoot>
<React.Suspense fallback={<div>加载中……</div>}>
<Routes childProps={childProps} />
</React.Suspense>
</RecoilRoot>
</ConfigProvider>
);
}
}
export default withRouter(App);
建立record.js文件
import {
atom,
selector,
} from 'recoil';
const TEXT_STATE = atom({
key: 'textState',
default: '',
});
const TEXT_STATE_COMPUTED = selector({
key: 'textStateChangeValue',
/**
* 1.若get内进行的是异步请求,则需要把promise对象返回出去
* 2.报错处理:throw ... 抛出错误
* 3.带参数查询:selector --> selectorFamily
*/
get: ({ get }) => {
const text = get(TEXT_STATE);
return new Promise((resolve, reject) => {
resolve(text.length)
})
},
// get: async ({ get }) => {
// const text = get(TEXT_STATE);
// const response = await new Promise((resolve, reject) => {
// resolve(text.length)
// })
// return response
// },
})
export default { TEXT_STATE, TEXT_STATE_COMPUTED };
export {
TEXT_STATE,
TEXT_STATE_COMPUTED
}
测试文件使用
text1
import React from "react";
import "./tese1.css";
import { TEXT_STATE,TEXT_STATE_COMPUTED } from "../../recoil/index";
import { useRecoilState, useRecoilValue } from "recoil";
import { Button } from 'antd';
function Test1(props) {
const [text, setText] = useRecoilState(TEXT_STATE);
const length = useRecoilValue(TEXT_STATE_COMPUTED)
const onChange = (event) => {
setText(event.target.value);
};
return (
<div>
<input type="text" value={text} onChange={onChange} />
<br />
输入值: {text}
<br />
输入值的长度: {length}
<br />
<Button type="primary" onClick={() => props.history.push('/test')}/>
</div>
);
}
export default Test1;
import React from "react";
import "./tese1.css";
import { TEXT_STATE } from "../../recoil/index";
import { useRecoilValue } from "recoil";
function Test2() {
const text = useRecoilValue(TEXT_STATE);
return (
<div>
<input type="text" defaultValue={text} />
<br />
Echo: {text}
</div>
);
}
export default Test2;