1. Context 基礎(chǔ)
參考:
2. mobx-react 基礎(chǔ)
參考:
- 官方文檔, https://github.com/mobxjs/mobx-react
- mobx官方文檔(文檔只能說不那么通俗易懂), https://cn.mobx.js.org/
3. Context 和 mobx 結(jié)合參考示例
參考:
4 具體實現(xiàn)
上面關(guān)于mobx
的文檔是真的很難讀,所以時間有限,長話短說,直接上代碼,其他的以后再補充
- 創(chuàng)建store容器和獲取store的函數(shù)
// store.js
import React, { createContext, useContext } from 'react'
import { observable, action, configure } from 'mobx'
import { useLocalStore } from 'mobx-react'
// 強制使用action
configure({enforceActions: 'observed'})
// 創(chuàng)建數(shù)據(jù)由于使用了裝飾器 所以使用class聲明
class Store {
@observable count = 0
// 注意this
@action
add = () => {
this.count += 1
}
@action.bound
reduce() {
this.count -= 1
}
}
// 創(chuàng)建context
const StoreContext = createContext(new Store())
// 創(chuàng)建context容器 就是一個函數(shù)組件
export const Provider = ({children}) => {
// useLocalStore的參數(shù)是一個函數(shù) 返回數(shù)據(jù)源
const store = useLocalStore(() => new Store())
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
}
// 其他組件獲取store
export const useStore = () => {
return useContext(StoreContext)
}
- 使用
store
容器
import React from 'react';
import ReactDOM from 'react-dom';
// 根組件
import App from './App';
// 引入store.js
import { Provider } from '@/mobx/store'
// 和redux很像 用上面創(chuàng)建的容器包裹根組件 這樣就能實現(xiàn)全局store
ReactDOM.render(<Provider><App/></Provider>, document.getElementById('root'));
- 在組件中使用
store
import React, {Fragment} from 'react'
import { observer } from 'mobx-react'
import { useStore } from '@/mobx/store'
// 這里是用的函數(shù)組件 class組件直接在上面用@observer就行了
const Home = observer((props) => {
const { count, add, reduce } = useStore()
return (
<Fragment>
<p>{count}</p>
<button onClick={() => {add()}}>+</button>
<button onClick={() => {reduce()}}>-</button>
</Fragment>
)
})
export default Home
下面總結(jié)一下步驟