RxJS状态管理

时间:2020-06-08 14:34:59

标签: reactjs rxjs

如何使用RxJS Observable保存React App的状态。将新项目添加到CRUD应用程序后刷新页面时,它没有在列表中保存新项目,添加的新项目消失了。根据应用的逻辑,页面刷新后,新项目应保存在本地存储中。

1 个答案:

答案 0 :(得分:0)

这是您如何做到的一个示例

const { useState, useEffect, useRef } = React;
const { BehaviorSubject, of, operators: { switchMap, tap } } = rxjs;

const mockLocalStorage = {
  values: `["one","two","three"]`,
  getItem(key) {
    return this.values
  },
  setItem(key, value) {
    this.values = value
  }
}

const App = () => {
  const [list, setList] = useState([]);
  const [value, setValue] = useState('');
  const ref = useRef(new BehaviorSubject(undefined));
  
  useEffect(() => {
    const subscription = ref.current
      .pipe(switchMap(_ => 
        of(JSON.parse(mockLocalStorage.getItem('key'))))
        )
      .subscribe(values => {
        setList(values);
      })
    
    return () => {
      subscription.unsubscribe();
    }
      
  }, [])
  
  const onChange = ({key, target: {value}}) => setValue(value)
  
  const addItem = ({key, target: {value}}) => {
    if (key !== 'Enter') {
      return;
    }
  
    const state = [...list, value];
    mockLocalStorage.setItem('key', JSON.stringify(state))
    ref.current.next(state);
    setValue('');
  }

return <div>
  {list.map(item => <div key={item}>{item}</div>)}
  <input type="text" value={value} onChange={onChange} onKeyDown={addItem} placeholder="Enter item and press enter..."/>
</div>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>
</script>
<div id="root"></div>